{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3.协程篇\n",
    "\n",
    "在线预览：<https://github.lesschina.com/python/base/concurrency/4.并发编程-协程篇.html>\n",
    "\n",
    "示例代码：<https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/ZCoroutine>\n",
    "\n",
    "多进程和多线程切换之间也是有资源浪费的，相比而言协程更轻量级\n",
    "\n",
    "## 3.1.知识回顾\n",
    "\n",
    "### 1.装饰器\n",
    "\n",
    "往期文章：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9333792.html#2.Python装饰器\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9333792.html#2.Python装饰器</a>\n",
    "\n",
    "基础拓展篇已经讲的很透彻了，就不再雷同了，贴一个简单案例，然后扩展说说**`可迭代`、`迭代器`和`生成器`**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "方法签名：login_out\n",
      "login_out log_info...\n",
      "已经退出登录\n",
      "已经退出登录\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "from functools import wraps\n",
    "\n",
    "def log(func):\n",
    "    @wraps(func)\n",
    "    def wrapper(*args,**kv):\n",
    "        print(\"%s log_info...\" % func.__name__)\n",
    "        return func(*args,**kv)\n",
    "    return wrapper\n",
    "\n",
    "@log\n",
    "def login_out():\n",
    "    print(\"已经退出登录\")\n",
    "\n",
    "def main():\n",
    "    # @wraps(func) 可以使得装饰前后，方法签名一致\n",
    "    print(f\"方法签名：{login_out.__name__}\")\n",
    "    login_out()\n",
    "    \n",
    "    # @wraps能让你通过属性 __wrapped__ 直接访问被包装函数\n",
    "    login_out.__wrapped__() # 执行原来的函数\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.迭代器\n",
    "\n",
    "往期文章：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#6.Python迭代器\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9278573.html#6.Python迭代器</a>\n",
    "\n",
    "过于基础的就不说了，简单说下，然后举一个`OOP`的`Demo`：\n",
    "1. **判断是否可迭代：（能不能for遍历）**\n",
    "    - `from collections.abc import Iterable`\n",
    "    - `isinstance(xxx, Iterable)`\n",
    "2. **判断是否是迭代器：（能不能`next(xxx)`遍历）**\n",
    "    - `from collections.abc import Iterator`\n",
    "    - `isinstance(xxx, Iterable)`\n",
    "    - PS：迭代器是一定可以迭代的\n",
    "3. **可迭代对象转迭代器：（生成器都是迭代器）**\n",
    "    - 把`list、dict、str`等`Iterable`变成`Iterator`可以使用`iter()`函数 eg：**`iter([])`**（节省资源）\n",
    "    - PS：生成器都是`Iterator`对象，但list、dict、str虽然是`Iterable`，却不是`Iterator`\n",
    "\n",
    "**提醒一下：`from collections import Iterable, Iterator # 现在已经不推荐使用了（3.8会弃用）`**\n",
    "\n",
    "查看一下`typing.py`的源码就知道了:\n",
    "```PY\n",
    "# 模仿collections.abc中的那些（Python3.7目前只是过渡的兼容版，没有具体实现）\n",
    "def _alias(origin, params, inst=True):\n",
    "    return _GenericAlias(origin, params, special=True, inst=inst)\n",
    "\n",
    "T_co = TypeVar('T_co', covariant=True)  # Any type covariant containers.\n",
    "\n",
    "Iterable = _alias(collections.abc.Iterable, T_co)\n",
    "Iterator = _alias(collections.abc.Iterator, T_co)\n",
    "```\n",
    "\n",
    "之前说了个 <a href=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#7.1.IEnumerator-%E5%92%8C-IEnumerable\" target=\"_blank\">CSharp 的 OOP Demo</a>，这次来个`Python`的，我们来一步步演变："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 导入相关模块\n",
    "from collections.abc import Iterable, Iterator\n",
    "# from collections import Iterable, Iterator # 现在已经不推荐使用了（3.8会弃用）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个Class\n",
    "class MyArray(object):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 是否可迭代 False\n",
    "isinstance(MyArray(),Iterable)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 是否是迭代器 False\n",
    "isinstance(MyArray(),Iterator)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 如果Class里面含有`__iter__`方法就是可迭代的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 重新定义测试：\n",
    "class MyArray(object):\n",
    "    def __iter__(self):\n",
    "        pass\n",
    "\n",
    "# 是否可迭代 False\n",
    "isinstance(MyArray(),Iterable)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 是否是迭代器 False\n",
    "isinstance(MyArray(),Iterator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**这时候依然不是迭代器**\n",
    "\n",
    "这个可以类比C#：\n",
    "1. 能不能foreach就看你遍历对象有没有实现IEnumerable，就说明你是不是一个可枚举类型（enumerator type）\n",
    "2. 是不是个枚举器（enumerator）就看你实现了IEnumerator接口没\n",
    "\n",
    "```csharp\n",
    "// 能不能foreach就看你遍历对象有没有实现IEnumerable，就说明你是不是一个可枚举类型\n",
    "public interface IEnumerable\n",
    "{\n",
    "    IEnumerator GetEnumerator();\n",
    "}\n",
    "\n",
    "// 是不是个枚举器（enumerator）就看你实现了IEnumerator接口没\n",
    "public interface IEnumerator\n",
    "{\n",
    "    object Current { get; }\n",
    "\n",
    "    bool MoveNext();\n",
    "\n",
    "    void Reset();\n",
    "}\n",
    "```\n",
    "先看看Python对于的类吧：\n",
    "```py\n",
    "# https://github.com/lotapp/cpython3/blob/master/Lib/_collections_abc.py\n",
    "class Iterable(metaclass=ABCMeta):\n",
    "\n",
    "    __slots__ = ()\n",
    "\n",
    "    @abstractmethod\n",
    "    def __iter__(self):\n",
    "        while False:\n",
    "            yield None\n",
    "\n",
    "    @classmethod\n",
    "    def __subclasshook__(cls, C):\n",
    "        if cls is Iterable:\n",
    "            return _check_methods(C, \"__iter__\")\n",
    "        return NotImplemented\n",
    "\n",
    "class Iterator(Iterable):\n",
    "\n",
    "    __slots__ = ()\n",
    "\n",
    "    @abstractmethod\n",
    "    def __next__(self):\n",
    "        'Return the next item from the iterator. When exhausted, raise StopIteration'\n",
    "        raise StopIteration\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    @classmethod\n",
    "    def __subclasshook__(cls, C):\n",
    "        if cls is Iterator:\n",
    "            return _check_methods(C, '__iter__', '__next__')\n",
    "        return NotImplemented\n",
    "```\n",
    "读源码的好处来了==>**`抽象方法：@abstractmethod（子类必须实现）`，上次漏讲了吧～**\n",
    "\n",
    "上面说**迭代器肯定可以迭代**，说很抽象，代码太直观了 (继承)：**`class Iterator(Iterable)`**\n",
    "\n",
    "现在我们来模仿并实现一个`Python`版本的`迭代器`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "True\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 先搭个空架子\n",
    "class MyIterator(Iterator):\n",
    "    def __next__(self):\n",
    "        pass\n",
    "\n",
    "class MyArray(Iterable):\n",
    "    def __iter__(self):\n",
    "        return MyIterator() # 返回一个迭代器\n",
    "\n",
    "def main():\n",
    "    # 可迭代 True\n",
    "    print(isinstance(MyArray(), Iterable))\n",
    "    # 迭代器也是可迭代的 True\n",
    "    print(isinstance(MyIterator(), Iterable))\n",
    "    # 是迭代器 True\n",
    "    print(isinstance(MyIterator(), Iterator))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 把迭代器简化合并\n",
    "class MyIterator(Iterator):\n",
    "    def __next__(self):\n",
    "        pass\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self # 返回一个迭代器(现在就是它自己了)\n",
    "\n",
    "def main():\n",
    "    print(isinstance(MyIterator(), Iterable))\n",
    "    print(isinstance(MyIterator(), Iterator))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n",
      "55\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 马上进入正题了，先回顾一下Fibona\n",
    "def fibona(n):\n",
    "    a, b = 0, 1\n",
    "    for i in range(n):\n",
    "        a, b = b, a+b\n",
    "        print(a)\n",
    "\n",
    "# 获取10个斐波拉契数列\n",
    "fibona(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "<__main__.FibonaIterator object at 0x000001CAFFD2C748>\n",
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n",
      "55\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 改造成迭代器\n",
    "from collections.abc import Iterable, Iterator\n",
    "\n",
    "class FibonaIterator(Iterator):\n",
    "    def __init__(self, n):\n",
    "        self.__a = 0\n",
    "        self.__b = 1\n",
    "        self.__n = n  # 获取多少个\n",
    "        self.__index = 0  # 当前索引\n",
    "\n",
    "    def __next__(self):\n",
    "        if self.__index < self.__n:\n",
    "            self.__index += 1\n",
    "            # 生成下一波\n",
    "            self.__a, self.__b = self.__b, self.__a + self.__b\n",
    "            return self.__a\n",
    "        else:\n",
    "            raise StopIteration # for循环结束条件\n",
    "\n",
    "def main():\n",
    "    print(FibonaIterator(10))\n",
    "    for i in FibonaIterator(10):\n",
    "        print(i)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "### 3.生成器\n",
    "\n",
    "往期文章：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#5.Python生成器\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9278573.html#5.Python生成器</a>\n",
    "\n",
    "生成器是啥？看源码就秒懂了：(**迭代器的基础上再封装**)\n",
    "```py\n",
    "class Generator(Iterator):\n",
    "    __slots__ = ()\n",
    "\n",
    "    def __next__(self):\n",
    "        \"\"\"从生成器返回下一个item，结束的时候抛出 StopIteration\"\"\"\n",
    "        return self.send(None)\n",
    "\n",
    "    @abstractmethod\n",
    "    def send(self, value):\n",
    "        \"\"\"将值发送到生成器。返回下一个产生的值或抛出StopIteration\"\"\"\n",
    "        raise StopIteration\n",
    "\n",
    "    @abstractmethod\n",
    "    def throw(self, typ, val=None, tb=None):\n",
    "        \"\"\"在生成器中引发异常。返回下一个产生的值或抛出StopIteration\"\"\"\n",
    "        if val is None:\n",
    "            if tb is None:\n",
    "                raise typ\n",
    "            val = typ()\n",
    "        if tb is not None:\n",
    "            val = val.with_traceback(tb)\n",
    "        raise val\n",
    "\n",
    "    # 现在知道之前close后为啥没异常了吧～\n",
    "    def close(self):\n",
    "        \"\"\"屏蔽异常\"\"\"\n",
    "        try:\n",
    "            self.throw(GeneratorExit)\n",
    "        except (GeneratorExit, StopIteration):\n",
    "            pass\n",
    "        else:\n",
    "            raise RuntimeError(\"generator ignored GeneratorExit\")\n",
    "\n",
    "    @classmethod\n",
    "    def __subclasshook__(cls, C):\n",
    "        if cls is Generator:\n",
    "            return _check_methods(C, '__iter__', '__next__',\n",
    "                                  'send', 'throw', 'close')\n",
    "        return NotImplemented\n",
    "```\n",
    "迭代器的基础上再封装了两个抽象方法`send`、`throw`和屏蔽异常的方法`close`\n",
    "\n",
    "现在用生成器的方式改写下斐波拉契数列：（列表推导式改成小括号是最简单的一种生成器）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "<generator object fibona at 0x000001CAFFD1AC00>\n",
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n",
      "55\n"
     ]
    }
   ],
   "source": [
    "% time\n",
    "\n",
    "# 代码瞬间就简洁了\n",
    "def fibona(n):\n",
    "    a = 0\n",
    "    b = 1\n",
    "    for _ in range(n):\n",
    "        a, b = b, a + b\n",
    "        yield a # 加个yiel就变成生成器了\n",
    "\n",
    "def main():\n",
    "    print(fibona(10))\n",
    "    for i in fibona(10):\n",
    "        print(i)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意下这几点：\n",
    "1. <a herf=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#5.3.扩展之～send(msg)方法：\" target=\"_blank\">generator刚启动的时候，要么 next()，要么 send(None)，不然会引发：</a>\n",
    "    - `TypeError: can't send non-None value to a just-started generator`\n",
    "2. <a herf=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#5.4.扩展之～return和break的说明\" target=\"_blank\">在一个generator函数中，遇到return或者break则直接抛出StopIteration终止迭代</a>\n",
    "    - 如果没有则默认执行至函数完毕\n",
    "3. 如果想要拿到返回值，必须捕获`StopIteration`错误，返回值包含在`StopIteration`的`value`中\n",
    "\n",
    "```py\n",
    "def test_send(n):\n",
    "    for i in range(n):\n",
    "        if i==2:\n",
    "            return \"i==2\"\n",
    "        yield i\n",
    "\n",
    "g = test_send(5)\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        tmp = next(g)\n",
    "        print(tmp)\n",
    "    except StopIteration as ex:\n",
    "        print(ex.value)\n",
    "        break\n",
    "```\n",
    "输出：\n",
    "```\n",
    "0\n",
    "1\n",
    "i==2\n",
    "```\n",
    "\n",
    "其他的也没什么好说的了，读完源码再看看之前讲的内容`别有一番滋味在心头`哦～"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 3.2.概念篇\n",
    "\n",
    "上集回顾：<a href=\"https://mp.weixin.qq.com/s/jWRBHi_ZNDBxOXElgAk86w\" target=\"_blank\">网络：静态服务器+压测</a>\n",
    "\n",
    "### 1.同步与异步\n",
    "\n",
    "> 同步是指一个任务的完成需要依赖另外一个任务时，只有等待被依赖的任务完成后，依赖的任务才能算完成。\n",
    "\n",
    "> 异步是指不需要等待被依赖的任务完成，只是通知被依赖的任务要完成什么工作。然后继续执行下面代码逻辑，只要自己完成了整个任务就算完成了（异步一般使用状态、通知和回调）\n",
    "\n",
    "PS：**项目里面一般是这样的**：（个人经验）\n",
    "1. 同步架构：一般都是和钱相关的需求，需要实时返回的业务\n",
    "2. 异步架构：更多是对写要求比较高时的场景（同步变异步）\n",
    "    - 读一般都是实时返回，代码一般都是`await xxx()`\n",
    "3. 想象个情景就清楚了：\n",
    "    - 异步：现在用户写了篇文章，可以异步操作，就算没真正写到数据库也可以返回：发表成功（大不了失败提示一下）\n",
    "    - 同步：用户获取订单信息，你如果异步就会这样了：提示下获取成功，然后一片空白...用户不卸载就怪了...\n",
    "\n",
    "### 2.阻塞与非阻塞\n",
    "\n",
    "> 阻塞是指调用结果返回之前，当前线程会被挂起，一直处于等待消息通知，不能够执行其他业务（大部分代码都是这样的）\n",
    "\n",
    "> 非阻塞是指在不能立刻得到结果之前，该函数不会阻塞当前线程，而会立刻返回（继续执行下面代码，或者重试机制走起）\n",
    "\n",
    "PS：**项目里面重试机制为啥一般都是3次？**\n",
    "1. 第一次重试，两台PC挂了也是有可能的\n",
    "2. 第二次重试，负载均衡分配的三台机器同时挂的可能性不是很大，这时候就有可能是网络有点拥堵了\n",
    "3. 最后一次重试，再失败就没意义了，日记写起来，再重试网络负担就加大了，得不偿失了\n",
    "\n",
    "### 3.五种IO模型\n",
    "\n",
    "对于一次IO访问，数据会先被拷贝到内核的缓冲区中，然后才会从内核的缓冲区拷贝到应用程序的地址空间。需要经历两个阶段：\n",
    "1. 准备数据\n",
    "2. 将数据从内核缓冲区拷贝到进程地址空间\n",
    "\n",
    "由于存在这两个阶段，Linux产生了下面五种IO模型（`以socket为例`）\n",
    "1. 阻塞式IO：\n",
    "    - 当用户进程调用了`recvfrom`等阻塞方法时，内核进入IO的第1个阶段：准备数据（内核需要等待足够的数据再拷贝）这个过程需要等待，用户进程会被阻塞，等内核将数据准备好，然后拷贝到用户地址空间，内核返回结果，用户进程才从阻塞态进入就绪态\n",
    "    - Linux中默认情况下所有的socket都是阻塞的\n",
    "2. 非阻塞式IO：\n",
    "    - 当用户进程发出read操作时，如果`kernel`中的数据还没有准备好，那么它并不会`block`用户进程，而是立刻返回一个`error`。\n",
    "    - 用户进程判断结果是一个`error`时，它就知道数据还没有准备好，于是它可以再次发送read操作\n",
    "    - 一旦`kernel`中的数据准备好了，并且又再次收到了用户进程的`system call`，那么它马上就将数据拷贝到了用户内存，然后返回\n",
    "    - 非阻塞IO模式下用户进程需要不断地询问内核的数据准备好了没有\n",
    "3. **IO多路复用**：\n",
    "    - 通过一种机制，一个进程可以监视多个文件描述符（套接字描述符）一旦某个文件描述符就绪（一般是读就绪或者写就绪），能够通知程序进行相应的读写操作（这样就不需要每个用户进程不断的询问内核数据准备好了没）\n",
    "    - 常用的IO多路复用方式有`select`、`poll`和`epoll`\n",
    "4. 信号驱动IO：（之前我们讲进程先导篇的时候说过）\n",
    "    - 内核文件描述符就绪后，通过信号通知用户进程，用户进程再通过系统调用读取数据。\n",
    "    - 此方式属于同步IO（实际读取数据到用户进程缓存的工作仍然是由用户进程自己负责的）\n",
    "5. **异步IO**（`POSIX`的`aio_`系列函数）\n",
    "    - 用户进程发起read操作之后，立刻就可以开始去做其它的事。内核收到一个异步`IO read`之后，会立刻返回，不会阻塞用户进程。\n",
    "    - 内核会等待数据准备完成，然后将数据拷贝到用户内存，当这一切都完成之后，内核会给用户进程发送一个`signal`告诉它read操作完成了\n",
    "\n",
    "### 4.Unix图示\n",
    "\n",
    "贴一下Unix编程里面的图：\n",
    "\n",
    "<center>非阻塞IO</center>\n",
    "\n",
    "![2.非阻塞IO.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181210212858009-948984805.png)\n",
    "\n",
    "<center>IO复用</center>\n",
    "\n",
    "![3.IO复用.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181210212908314-1267377747.png)\n",
    "\n",
    "<center>信号IO</center>\n",
    "\n",
    "![4.信号IO.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181210212934040-13536334.png)\n",
    "\n",
    "<center>异步AIO</center>\n",
    "\n",
    "![5.异步AIO.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181210212944334-1184572641.png)\n",
    "\n",
    "## 3.3.IO多路复用\n",
    "\n",
    "开始之前咱们通过非阻塞IO引入一下：（来个简单例子`socket.setblocking(False)`)\n",
    "```py\n",
    "import time\n",
    "import socket\n",
    "\n",
    "def select(socket_addr_list):\n",
    "    for client_socket, client_addr in socket_addr_list:\n",
    "        try:\n",
    "            data = client_socket.recv(2048)\n",
    "            if data:\n",
    "                print(f\"[来自{client_addr}的消息：]\\n\")\n",
    "                print(data.decode(\"utf-8\"))\n",
    "                client_socket.send(\n",
    "                    b\"HTTP/1.1 200 ok\\r\\nContent-Type: text/html;charset=utf-8\\r\\n\\r\\n<h1>Web Server Test</h1>\"\n",
    "                )\n",
    "            else:\n",
    "                # 没有消息是触发异常，空消息是断开连接\n",
    "                client_socket.close()  # 关闭客户端连接\n",
    "                socket_addr_list.remove((client_socket, client_addr))\n",
    "                print(f\"[客户端{client_addr}已断开连接，当前连接数：{len(socket_addr_list)}]\")\n",
    "        except Exception:\n",
    "            pass\n",
    "\n",
    "def main():\n",
    "    # 存放客户端集合\n",
    "    socket_addr_list = list()\n",
    "\n",
    "    with socket.socket() as tcp_server:\n",
    "        # 防止端口绑定的设置\n",
    "        tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n",
    "        tcp_server.bind(('', 8080))\n",
    "        tcp_server.listen()\n",
    "        tcp_server.setblocking(False)  # 服务端非阻塞\n",
    "        while True:\n",
    "            try:\n",
    "                client_socket, client_addr = tcp_server.accept()\n",
    "                client_socket.setblocking(False)  # 客户端非阻塞\n",
    "                socket_addr_list.append((client_socket, client_addr))\n",
    "            except Exception:\n",
    "                pass\n",
    "            else:\n",
    "                print(f\"[来自{client_addr}的连接，当前连接数：{len(socket_addr_list)}]\")\n",
    "            # 防止客户端断开后出错\n",
    "            if socket_addr_list:\n",
    "                # 轮询查看客户端有没有消息\n",
    "                select(socket_addr_list)  # 引用传参\n",
    "                time.sleep(0.01)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "![6.nowait.gif](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181210110004422-72437374.gif)\n",
    "\n",
    "可以思考下：\n",
    "1. 为什么Server也要设置为非阻塞？\n",
    "    - PS：一个线程里面只能有一个死循环，现在程序需要两个死循环，so ==> 放一起咯\n",
    "2. 断开连接怎么判断？\n",
    "    - PS：没有消息是触发异常，空消息是断开连接\n",
    "3. client_socket为什么不用dict存放？\n",
    "    - PS：dict在循环的过程中，del会引发异常\n",
    "\n",
    "### 1.Select\n",
    "\n",
    "select和上面的有点类似，就是轮询的过程交给了操作系统：\n",
    "> kernel会“监视”所有select负责的socket，当任何一个socket中的数据准备好了，select就会返回。这个时候用户进程再调用read操作，将数据从kernel拷贝到用户进程\n",
    "\n",
    "来个和上面等同的案例：\n",
    "```py\n",
    "import select\n",
    "import socket\n",
    "\n",
    "def main():\n",
    "    with socket.socket() as tcp_server:\n",
    "        tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n",
    "        tcp_server.bind(('', 8080))\n",
    "        tcp_server.listen()\n",
    "        socket_info_dict = dict()\n",
    "        socket_list = [tcp_server]  # 监测列表\n",
    "        while True:\n",
    "            # 劣势：select列表数量有限制\n",
    "            read_list, write_list, error_list = select.select(\n",
    "                socket_list, [], [])\n",
    "            for item in read_list:\n",
    "                # 服务端迎接新的连接\n",
    "                if item == tcp_server:\n",
    "                    client_socket, client_address = item.accept()\n",
    "                    socket_list.append(client_socket)\n",
    "                    socket_info_dict[client_socket] = client_address\n",
    "                    print(f\"[{client_address}已连接，当前连接数：{len(socket_list)-1}]\")\n",
    "                # 客户端发来\n",
    "                else:\n",
    "                    data = item.recv(2048)\n",
    "                    if data:\n",
    "                        print(data.decode(\"utf-8\"))\n",
    "                        item.send(\n",
    "                            b\"HTTP/1.1 200 ok\\r\\nContent-Type: text/html;charset=utf-8\\r\\n\\r\\n<h1>Web Server Test</h1>\"\n",
    "                        )\n",
    "                    else:\n",
    "                        item.close()\n",
    "                        socket_list.remove(item)\n",
    "                        info = socket_info_dict[item]\n",
    "                        print(f\"[{info}已断开，当前连接数：{len(socket_list)-1}]\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "**输出和上面一样**\n",
    "\n",
    "扩展说明：\n",
    "> select 函数监视的文件描述符分3类，分别是`writefds`、`readfds`、和`exceptfds`。调用后select函数会阻塞，直到有描述符就绪函数返回（**有数据可读、可写、或者有except**）或者超时（timeout指定等待时间，如果立即返回设为null即可）\n",
    "\n",
    "> select的一个缺点在于单个进程能够监视的文件描述符的数量存在最大限制，在Linux上一般为1024（64位=>2048）\n",
    "\n",
    "**然后Poll就出现了，就是把上限给去掉了，本质并没变，还是使用的`轮询`**\n",
    "\n",
    "### 2.EPoll\n",
    "\n",
    "> epoll在内核2.6中提出（Linux独有），使用一个文件描述符管理多个描述符，将用户关心的文件描述符的事件存放到内核的一个事件表中，采用监听回调的机制，这样在用户空间和内核空间的copy只需一次，避免再次遍历就绪的文件描述符列表\n",
    "\n",
    "先来看个案例吧：（输出和上面一样）\n",
    "```py\n",
    "import socket\n",
    "import select\n",
    "\n",
    "def main():\n",
    "    with socket.socket() as tcp_server:\n",
    "        tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n",
    "        tcp_server.bind(('', 8080))\n",
    "        tcp_server.listen()\n",
    "\n",
    "        # epoll是linux独有的\n",
    "        epoll = select.epoll()\n",
    "        # tcp_server注册到epoll中\n",
    "        epoll.register(tcp_server.fileno(), select.EPOLLIN | select.EPOLLET)\n",
    "\n",
    "        # key-value\n",
    "        fd_socket_dict = dict()\n",
    "\n",
    "        # 回调需要自己处理\n",
    "        while True:\n",
    "            # 返回可读写的socket fd 集合\n",
    "            poll_list = epoll.poll()\n",
    "            for fd, event in poll_list:\n",
    "                # 服务器的socket\n",
    "                if fd == tcp_server.fileno():\n",
    "                    client_socket, client_addr = tcp_server.accept()\n",
    "                    fd = client_socket.fileno()\n",
    "                    fd_socket_dict[fd] = (client_socket, client_addr)\n",
    "                    # 把客户端注册进epoll中\n",
    "                    epoll.register(fd, select.EPOLLIN | select.EPOLLET)\n",
    "                else:  # 客户端\n",
    "                    client_socket, client_addr = fd_socket_dict[fd]\n",
    "                    data = client_socket.recv(2048)\n",
    "                    print(\n",
    "                        f\"[来自{client_addr}的消息，当前连接数：{len(fd_socket_dict)}]\\n\")\n",
    "                    if data:\n",
    "                        print(data.decode(\"utf-8\"))\n",
    "                        client_socket.send(\n",
    "                            b\"HTTP/1.1 200 ok\\r\\nContent-Type: text/html;charset=utf-8\\r\\n\\r\\n<h1>Web Server Test</h1>\"\n",
    "                        )\n",
    "                    else:\n",
    "                        del fd_socket_dict[fd]\n",
    "                        print(\n",
    "                            f\"[{client_addr}已离线，当前连接数：{len(fd_socket_dict)}]\\n\"\n",
    "                        )\n",
    "                        # 从epoll中注销\n",
    "                        epoll.unregister(fd)\n",
    "                        client_socket.close()\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "扩展：**epoll的两种工作模式**\n",
    "> LT（level trigger，水平触发）模式：当epoll_wait检测到描述符就绪，将此事件通知应用程序，应用程序可以不立即处理该事件。下次调用epoll_wait时，会再次响应应用程序并通知此事件。LT模式是默认的工作模式。\n",
    "> LT模式同时支持阻塞和非阻塞socket。\n",
    "\n",
    "> ET（edge trigger，边缘触发）模式：当epoll_wait检测到描述符就绪，将此事件通知应用程序，应用程序必须立即处理该事件。如果不处理，下次调用epoll_wait时，不会再次响应应用程序并通知此事件。\n",
    "> ET是高速工作方式，只支持非阻塞socket（ET模式减少了epoll事件被重复触发的次数，因此效率要比LT模式高）\n",
    "\n",
    "**Code提炼一下**：\n",
    "1. 实例化对象：`epoll = select.epoll()`\n",
    "2. 注册对象：`epoll.register(tcp_server.fileno(), select.EPOLLIN | select.EPOLLET)`\n",
    "3. 注销对象：`epoll.unregister(fd)`\n",
    "\n",
    "PS：`epoll`不一定比`Select`性能高，一般都是分场景的：\n",
    "1. 高并发下，连接活跃度不高时：epoll比Select性能高（eg：web请求，页面随时关闭）\n",
    "2. 并发不高，连接活跃度比较高：Select更合适（eg：小游戏）\n",
    "3. **Select是win和linux通用的，而epoll只有linux有**\n",
    "\n",
    "其实IO多路复用还有一个`kqueue`，和`epoll`类似，下面的通用写法中有包含\n",
    "\n",
    "---\n",
    "\n",
    "### 3.通用写法（`Selector`）\n",
    "\n",
    "一般来说：**Linux下使用epoll，Win下使用select**（IO多路复用会这个通用的即可）\n",
    "\n",
    "先看看Python源代码：\n",
    "```py\n",
    "# 选择级别：epoll|kqueue|devpoll > poll > select\n",
    "if 'KqueueSelector' in globals():\n",
    "    DefaultSelector = KqueueSelector\n",
    "elif 'EpollSelector' in globals():\n",
    "    DefaultSelector = EpollSelector\n",
    "elif 'DevpollSelector' in globals():\n",
    "    DefaultSelector = DevpollSelector\n",
    "elif 'PollSelector' in globals():\n",
    "    DefaultSelector = PollSelector\n",
    "else:\n",
    "    DefaultSelector = SelectSelector\n",
    "```\n",
    "\n",
    "**实战案例**：(可读和可写可以不分开)\n",
    "```py\n",
    "import socket\n",
    "import selectors\n",
    "\n",
    "# Linux下使用epoll，Win下使用select\n",
    "Selector = selectors.DefaultSelector()\n",
    "\n",
    "class Task(object):\n",
    "    def __init__(self):\n",
    "        # 存放客户端fd和socket键值对\n",
    "        self.fd_socket_dict = dict()\n",
    "\n",
    "    def run(self):\n",
    "        self.server = socket.socket()\n",
    "        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n",
    "        self.server.bind(('', 8080))\n",
    "        self.server.listen()\n",
    "        # 把Server注册到epoll\n",
    "        Selector.register(self.server.fileno(), selectors.EVENT_READ,\n",
    "                          self.connected)\n",
    "\n",
    "    def connected(self, key):\n",
    "        \"\"\"客户端连接时处理\"\"\"\n",
    "        client_socket, client_address = self.server.accept()\n",
    "        fd = client_socket.fileno()\n",
    "        self.fd_socket_dict[fd] = (client_socket, client_address)\n",
    "        # 注册一个客户端读的事件（服务端去读消息）\n",
    "        Selector.register(fd, selectors.EVENT_READ, self.call_back_reads)\n",
    "        print(f\"{client_address}已连接，当前连接数：{len(self.fd_socket_dict)}\")\n",
    "\n",
    "    def call_back_reads(self, key):\n",
    "        \"\"\"客户端可读时处理\"\"\"\n",
    "        # 一个fd只能注册一次，监测可写的时候需要把可读给注销\n",
    "        Selector.unregister(key.fd)\n",
    "        client_socket, client_address = self.fd_socket_dict[key.fd]\n",
    "        print(f\"[来自{client_address}的消息:]\\n\")\n",
    "        data = client_socket.recv(2048)\n",
    "        if data:\n",
    "            print(data.decode(\"utf-8\"))\n",
    "            # 注册一个客户端写的事件（服务端去发消息）\n",
    "            Selector.register(key.fd, selectors.EVENT_WRITE,\n",
    "                              self.call_back_writes)\n",
    "        else:\n",
    "            client_socket.close()\n",
    "            del self.fd_socket_dict[key.fd]\n",
    "            print(f\"{client_address}已断开，当前连接数：{len(self.fd_socket_dict)}\")\n",
    "\n",
    "    def call_back_writes(self, key):\n",
    "        \"\"\"客户端可写时处理\"\"\"\n",
    "        Selector.unregister(key.fd)\n",
    "        client_socket, client_address = self.fd_socket_dict[key.fd]\n",
    "        client_socket.send(b\"ok\")\n",
    "        Selector.register(key.fd, selectors.EVENT_READ, self.call_back_reads)\n",
    "\n",
    "def main():\n",
    "    t = Task()\n",
    "    t.run()\n",
    "    while True:\n",
    "        ready = Selector.select()\n",
    "        for key, obj in ready:\n",
    "            # 需要自己回调\n",
    "            call_back = key.data\n",
    "            call_back(key)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "**Code提炼一下**：\n",
    "1. 实例化对象：`Selector = selectors.DefaultSelector()`\n",
    "2. 注册对象：\n",
    "    - `Selector.register(server.fileno(), selectors.EVENT_READ, call_back)`\n",
    "    - `Selector.register(server.fileno(), selectors.EVENT_WRITE, call_back)`\n",
    "3. 注销对象：`Selector.unregister(key.fd)`\n",
    "4. 注意一下：**一个fd只能注册一次，监测可写的时候需要把可读给注销（反之一样）**\n",
    "\n",
    "业余拓展：\n",
    "```\n",
    "select, iocp, epoll,kqueue及各种I/O复用机制\n",
    "https://blog.csdn.net/shallwake/article/details/5265287\n",
    "\n",
    "kqueue用法简介\n",
    "http://www.cnblogs.com/luminocean/p/5631336.html\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 3.4.协程引入\n",
    "\n",
    "### 1.yield from\n",
    "\n",
    "我们经常有这样的需求：`读取两个分表的数据列表，然后合并之后进行一些处理`\n",
    "\n",
    "平时可以借用`itertools.chain`来遍历：\n",
    "```py\n",
    "# https://docs.python.org/3/library/itertools.html#itertools.chain\n",
    "import itertools\n",
    "\n",
    "def main():\n",
    "    # 模拟分表后的两个查询结果\n",
    "    user1 = [\"小张\", \"小明\"]\n",
    "    user2 = [\"小潘\", \"小周\"]\n",
    "    # dict只能遍历key（这种情况需要自己封装合并方法并处理下）\n",
    "    user3 = {\"name\": \"test1\", \"name1\": \"test2\"}\n",
    "    \n",
    "    # 需求：合并并遍历\n",
    "    for item in itertools.chain(user1, user2, user3):\n",
    "        print(item)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小张\n",
    "小明\n",
    "小潘\n",
    "小周\n",
    "name\n",
    "name1\n",
    "```\n",
    "\n",
    "它的内部实现其实是这样的：（`相当于两层遍历，用yield返回`）\n",
    "```py\n",
    "def my_chain(*args, **kwargs):\n",
    "    for items in args:\n",
    "        for item in items:\n",
    "            yield item\n",
    "\n",
    "def main():\n",
    "    # 模拟分表后的两个查询结果\n",
    "    user1 = [\"小张\", \"小明\"]\n",
    "    user2 = [\"小潘\", \"小周\"]\n",
    "    # dict只能遍历key（这种情况需要自己封装合并方法并处理下）\n",
    "    user3 = {\"name\": \"test1\", \"name1\": \"test2\"}\n",
    "    \n",
    "    # 需求：合并并遍历\n",
    "    for item in my_chain(user1, user2, user3):\n",
    "        print(item)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "\n",
    "然后`Python3.3`之后语法再一步简化（**`yield from iterable对象`**）\n",
    "\n",
    "```py\n",
    "def my_chain(*args, **kwargs):\n",
    "    for items in args:\n",
    "        yield from items\n",
    "\n",
    "def main():\n",
    "    # 模拟分表后的两个查询结果\n",
    "    user1 = [\"小张\", \"小明\"]\n",
    "    user2 = [\"小潘\", \"小周\"]\n",
    "    \n",
    "    # 需求：合并并遍历\n",
    "    for item in my_chain(user1, user2):\n",
    "        print(item)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小张\n",
    "小明\n",
    "小潘\n",
    "小周\n",
    "test1\n",
    "test2\n",
    "```\n",
    "\n",
    "#### 扩展（可忽略）\n",
    "\n",
    "其实知道了内部实现，很容易就写上一段应对的处理：\n",
    "```py\n",
    "def my_chain(*args, **kwargs):\n",
    "    for my_iterable in args:\n",
    "        # 如果是字典类型就返回value\n",
    "        if isinstance(my_iterable, dict):\n",
    "            my_iterable = my_iterable.values()\n",
    "        for item in my_iterable:\n",
    "            yield item\n",
    "\n",
    "def main():\n",
    "    # 模拟分表后的两个查询结果\n",
    "    user1 = [\"小张\", \"小明\"]\n",
    "    user2 = [\"小潘\", \"小周\"]\n",
    "    # dict只能遍历key（这种情况需要自己封装合并方法并处理下）\n",
    "    user3 = {\"name\": \"test1\", \"name1\": \"test2\"}\n",
    "    # 需求：合并并遍历\n",
    "    for item in my_chain(user1, user2, user3):\n",
    "        print(item)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小张\n",
    "小明\n",
    "小潘\n",
    "小周\n",
    "test1\n",
    "test2\n",
    "```\n",
    "#### 扩展的正确处理\n",
    "\n",
    "PS：一般不会这么干的，一般都是`[{},{}]`遍历并处理：\n",
    "```py\n",
    "import itertools\n",
    "\n",
    "def main():\n",
    "    # 模拟分表后的两个查询结果\n",
    "    user1 = [{\"name\": \"小张\"}, {\"name\": \"小明\"}]\n",
    "    user2 = [{\"name\": \"小潘\"}, {\"name\": \"小周\"}]\n",
    "    user3 = [{\"name\": \"test1\"}, {\"name\": \"test2\"}]\n",
    "    # 需求：合并并遍历\n",
    "    for item in itertools.chain(user1, user2, user3):\n",
    "        # 一般都是直接在这里进行处理\n",
    "        for key, value in item.items():\n",
    "            print(value)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "\n",
    "### 1.yield版协程\n",
    "\n",
    "协程的目的其实很简单：**像写同步代码那样实现异步编程**\n",
    "\n",
    "先看个需求：**生成绘图的数据（`max,min,avg`）**\n",
    "\n",
    "比如说原来数据是这样的：\n",
    "```py\n",
    "products = [{\n",
    "    \"id\": 2344,\n",
    "    \"title\": \"御泥坊补水面膜\",\n",
    "    \"price\": [89, 76, 120, 99]\n",
    "}, {\n",
    "    \"id\": 2345,\n",
    "    \"title\": \"御泥坊火山泥面膜\",\n",
    "    \"price\": [30, 56, 70, 89]\n",
    "}]\n",
    "```\n",
    "处理之后：\n",
    "```py\n",
    "new_products = [{\n",
    "    \"id\": 2344,\n",
    "    \"title\": \"御泥坊补水面膜\",\n",
    "    \"price\": [89, 76, 120, 99],\n",
    "    \"max\": 120,\n",
    "    \"min\": 76,\n",
    "    \"avg\": 96.0\n",
    "},\n",
    "{\n",
    "    \"id\": 2345,\n",
    "    \"title\": \"御泥坊火山泥面膜\",\n",
    "    \"price\": [30, 56, 70, 89],\n",
    "    \"max\": 89,\n",
    "    \"min\": 30,\n",
    "    \"avg\": 61.25\n",
    "}]\n",
    "```\n",
    "\n",
    "处理过的数据一般用来画图，实际效果类似于：\n",
    "![1.需求.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181211133211122-601142215.png)\n",
    "\n",
    "如果不借助协程，我们一般这么处理：（数据库获取过程省略）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'id': 2344, 'title': '御泥坊补水面膜', 'price': [89, 76, 120, 99], 'avg': 96.0, 'max': 120, 'min': 76}, {'id': 2345, 'title': '御泥坊火山泥面膜', 'price': [30, 56, 70, 89], 'avg': 61.25, 'max': 89, 'min': 30}]\n"
     ]
    }
   ],
   "source": [
    "# 生成新的dict数据\n",
    "def get_new_item(item):\n",
    "    prices = item[\"price\"]\n",
    "    item[\"avg\"] = sum(prices) / len(prices)\n",
    "    item[\"max\"] = max(prices)\n",
    "    item[\"min\"] = min(prices)\n",
    "    return item\n",
    "\n",
    "def get_new_data(data):\n",
    "    newdata = []\n",
    "    for item in data:\n",
    "        new_item = get_new_item(item)\n",
    "        # print(new_item) # 处理后的新dict\n",
    "        newdata.append(new_item)\n",
    "    return newdata\n",
    "\n",
    "def main():\n",
    "    # 需求：生成绘图的数据（max,min,avg）\n",
    "    products = [{\n",
    "        \"id\": 2344,\n",
    "        \"title\": \"御泥坊补水面膜\",\n",
    "        \"price\": [89, 76, 120, 99]\n",
    "    }, {\n",
    "        \"id\": 2345,\n",
    "        \"title\": \"御泥坊火山泥面膜\",\n",
    "        \"price\": [30, 56, 70, 89]\n",
    "    }]\n",
    "\n",
    "    new_products = get_new_data(products)\n",
    "    print(new_products)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "改成yield版的协程也很方便，基本上代码没有变，也不用像IO多路复用那样来回的回调"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'id': 2344, 'title': '御泥坊补水面膜', 'price': [89, 76, 120, 99], 'avg': 96.0, 'max': 120, 'min': 76}, {'id': 2345, 'title': '御泥坊火山泥面膜', 'price': [30, 56, 70, 89], 'avg': 61.25, 'max': 89, 'min': 30}]\n"
     ]
    }
   ],
   "source": [
    "# 生成新的dict数据\n",
    "def get_new_item(item):\n",
    "    prices = item[\"price\"]\n",
    "    item[\"avg\"] = sum(prices) / len(prices)\n",
    "    item[\"max\"] = max(prices)\n",
    "    item[\"min\"] = min(prices)\n",
    "    yield item\n",
    "\n",
    "def get_new_data(data):\n",
    "    for item in data:\n",
    "        yield from get_new_item(item)\n",
    "\n",
    "def main():\n",
    "    # 需求：生成绘图的数据（max,min,avg）\n",
    "    products = [{\n",
    "        \"id\": 2344,\n",
    "        \"title\": \"御泥坊补水面膜\",\n",
    "        \"price\": [89, 76, 120, 99]\n",
    "    }, {\n",
    "        \"id\": 2345,\n",
    "        \"title\": \"御泥坊火山泥面膜\",\n",
    "        \"price\": [30, 56, 70, 89]\n",
    "    }]\n",
    "    new_products = list()\n",
    "    # 如果需要返回值就捕获StopIteration异常\n",
    "    for item in get_new_data(products):\n",
    "        new_products.append(item)\n",
    "    print(new_products)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "简单解析一下：（用`yield from`的目的就是为了引出等会说的`async/await`）\n",
    "\n",
    "**`yield from`（委托生成器`get_new_data`）的好处就是让调用方（`main`）和`yield`子生成器(`get_new_item`)直接建立一个双向通道**\n",
    "\n",
    "你也可以把`yield from`当作一个中介(**如果不理解就把`yield from`想象成`await`就容易理解了**)，本质就是下面代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'id': 2344, 'title': '御泥坊补水面膜', 'price': [89, 76, 120, 99], 'avg': 96.0, 'max': 120, 'min': 76}, {'id': 2345, 'title': '御泥坊火山泥面膜', 'price': [30, 56, 70, 89], 'avg': 61.25, 'max': 89, 'min': 30}]\n"
     ]
    }
   ],
   "source": [
    "# 生成新的数据\n",
    "def get_new_data(data):\n",
    "    for item in data:\n",
    "        prices = item[\"price\"]\n",
    "        item[\"avg\"] = sum(prices) / len(prices)\n",
    "        item[\"max\"] = max(prices)\n",
    "        item[\"min\"] = min(prices)\n",
    "        yield item\n",
    "\n",
    "\n",
    "def main():\n",
    "    # 需求：生成绘图的数据（max,min,avg）\n",
    "    products = [{\n",
    "        \"id\": 2344,\n",
    "        \"title\": \"御泥坊补水面膜\",\n",
    "        \"price\": [89, 76, 120, 99]\n",
    "    }, {\n",
    "        \"id\": 2345,\n",
    "        \"title\": \"御泥坊火山泥面膜\",\n",
    "        \"price\": [30, 56, 70, 89]\n",
    "    }]\n",
    "    new_products = list()\n",
    "    for item in get_new_data(products):\n",
    "        new_products.append(item)\n",
    "    print(new_products)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### PEP 380（含分析）\n",
    "\n",
    "`yield from`内部其实在`yield`基础上做了很多事情（比如一些异常的处理），具体可以看看 **<a href=\"https://www.python.org/dev/peps/pep-0380/\" target=\"_blank\">PEP 380</a>**\n",
    "\n",
    "先提炼一个`简版`的：\n",
    "```py\n",
    "# 正常调用\n",
    "RESULT = yield from EXPR\n",
    "\n",
    "# _i：子生成器（也是个迭代器）\n",
    "# _y：子生成器生产的值\n",
    "# _r：yield from 表达式最终结果\n",
    "# _s：调用方通过send发送的值\n",
    "# _e：异常对象\n",
    "\n",
    "# 内部原理\n",
    "_i = iter(EXPR) # EXPR是一个可迭代对象，_i是子生成器\n",
    "try:\n",
    "    # 第一次不能send值，只能next() or send(None)，并把产生的值放到_y中\n",
    "    _y = next(_i)\n",
    "except StopIteration as _e:\n",
    "    # 如果子生成器直接就return了，那就会抛出异常，通过value可以拿到子生成器的返回值\n",
    "    _r = _e.value\n",
    "else:\n",
    "    # 尝试进行循环（调用方和子生成器交互过程），yield from这个生成器会阻塞（委托生成器）\n",
    "    while 1:\n",
    "        # 这时候子生成器已经和调用方建立了双向通道，在等待调用方send(value)，把这个值保存在_s中\n",
    "        _s = yield _y # 这边还会进行一系列异常处理，我先删掉，等会看\n",
    "        try:\n",
    "            # 如果send(None)，那么继续next遍历\n",
    "            if _s is None:\n",
    "                _y = next(_i) # 把子生成器结果放到 _y 中\n",
    "            else:\n",
    "                _y = _i.send(_s) # 如果调用方send一个值，就转发到子生成器\n",
    "        except StopIteration as _e:\n",
    "            _r = _e.value # 如果子生成器遍历完了，就把返回值给_r\n",
    "            break\n",
    "RESULT = _r # 最终的返回值（yield from 最终的返回值）\n",
    "```\n",
    "\n",
    "现在再来看`完整版`压力就没有那么大了：\n",
    "\n",
    "```py\n",
    "# 正常调用\n",
    "RESULT = yield from EXPR\n",
    "\n",
    "# _i：子生成器（也是个迭代器）\n",
    "# _y：子生成器生产的值\n",
    "# _r：yield from 表达式最终结果\n",
    "# _s：调用方通过send发送的值\n",
    "# _e：异常对象\n",
    "\n",
    "# 内部原理\n",
    "_i = iter(EXPR) # EXPR是一个可迭代对象，_i是子生成器\n",
    "try:\n",
    "    # 第一次不能send值，只能next() or send(None)，并把产生的值放到_y中\n",
    "    _y = next(_i)\n",
    "except StopIteration as _e:\n",
    "    # 如果子生成器直接就return了，那就会抛出异常，通过value可以拿到子生成器的返回值\n",
    "    _r = _e.value\n",
    "else:\n",
    "    # 尝试进行循环（调用方和子生成器交互过程），yield from这个生成器会阻塞（委托生成器）\n",
    "    while 1:\n",
    "        try:\n",
    "            # 这时候子生成器已经和调用方建立了双向通道，在等待调用方send(value)，把这个值保存在_s中\n",
    "            _s = yield _y\n",
    "        \n",
    "        # 【现在补全】有这么几种情况需要处理\n",
    "        # 1.子生成器可能只是一个迭代器，并不能作为协程的生成器（不支持throw和close）\n",
    "        # 2.子生成器虽然支持了throw和close，但在子生成器内部两种方法都会抛出异常\n",
    "        # 3.调用法调用了gen.throw()，想让子生成器自己抛异常\n",
    "        # 这时候就要处理 gen.close() 和 gen.throw()的情况\n",
    "        \n",
    "        # 生成器close()异常的处理\n",
    "        except GeneratorExit as _e:\n",
    "            try:\n",
    "                _m = _i.close\n",
    "            except AttributeError:\n",
    "                pass # 屏蔽close的异常\n",
    "            else:\n",
    "                _m()\n",
    "            raise _e # 上抛异常\n",
    "        # 生成器throw()异常的处理\n",
    "        except BaseException as _e:\n",
    "            _x = sys.exc_info()\n",
    "            try:\n",
    "                _m = _i.throw\n",
    "            except AttributeError:\n",
    "                raise _e\n",
    "            else:\n",
    "                try:\n",
    "                    _y = _m(*_x)\n",
    "                except StopIteration as _e:\n",
    "                    _r = _e.value\n",
    "                    break\n",
    "        else:\n",
    "            try:\n",
    "                # 如果send(None)，那么继续next遍历\n",
    "                if _s is None:\n",
    "                    _y = next(_i) # 把子生成器结果放到 _y 中\n",
    "                else:\n",
    "                    _y = _i.send(_s) # 如果调用方send一个值，就转发到子生成器\n",
    "            except StopIteration as _e:\n",
    "                _r = _e.value # 如果子生成器遍历完了，就把返回值给_r\n",
    "                break\n",
    "RESULT = _r # 最终的返回值（yield from 最终的返回值）\n",
    "```\n",
    "\n",
    "### 2.async/await\n",
    "\n",
    "把上面的原生代码用`async和await`改装一下：(**协程的目的就是像写同步代码一样写异步，这个才算是真做到了**)\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 生成新的dict数据\n",
    "async def get_new_item(item):\n",
    "    prices = item[\"price\"]\n",
    "    item[\"avg\"] = sum(prices) / len(prices)\n",
    "    item[\"max\"] = max(prices)\n",
    "    item[\"min\"] = min(prices)\n",
    "    return item\n",
    "\n",
    "async def get_new_data(data):\n",
    "    newdata = []\n",
    "    for item in data:\n",
    "        new_item = await get_new_item(item)\n",
    "        # print(new_item) # 处理后的新dict\n",
    "        newdata.append(new_item)\n",
    "    return newdata\n",
    "\n",
    "def main():\n",
    "    # 需求：生成绘图的数据（max,min,avg）\n",
    "    products = [{\n",
    "        \"id\": 2344,\n",
    "        \"title\": \"御泥坊补水面膜\",\n",
    "        \"price\": [89, 76, 120, 99]\n",
    "    }, {\n",
    "        \"id\": 2345,\n",
    "        \"title\": \"御泥坊火山泥面膜\",\n",
    "        \"price\": [30, 56, 70, 89]\n",
    "    }]\n",
    "    \n",
    "    # python 3.7\n",
    "    new_products = asyncio.run(get_new_data(products))\n",
    "    print(new_products)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：（是不是很原生代码没啥区别？）\n",
    "```\n",
    "[{'id': 2344, 'title': '御泥坊补水面膜', 'price': [89, 76, 120, 99], 'avg': 96.0, 'max': 120, 'min': 76}, \n",
    "{'id': 2345, 'title': '御泥坊火山泥面膜', 'price': [30, 56, 70, 89], 'avg': 61.25, 'max': 89, 'min': 30}]\n",
    "```\n",
    "\n",
    "下级预估：**asyncio**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 3.5.asyncio\n",
    "\n",
    "官方文档：<a href=\"https://docs.python.org/3/library/asyncio.html\" target=\"_blank\">https://docs.python.org/3/library/asyncio.html</a>\n",
    "\n",
    "开发中常见错误：<a href=\"https://docs.python.org/3/library/asyncio-dev.html\" target=\"_blank\">https://docs.python.org/3/library/asyncio-dev.html</a>\n",
    "\n",
    "代码示例：<https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/ZCoroutine>\n",
    "\n",
    "**PS：`asyncio`是`Python`用于解决`异步IO`编程的`一整套`解决方案**\n",
    "\n",
    "### 3.5.1.上节回顾\n",
    "\n",
    "上次说了下<a href=\"https://mp.weixin.qq.com/s/5d701WQG1L8mDOO-bnKXdQ\" target=\"_blank\">协程演变过程</a>，这次继续，先接着上次的说：\n",
    "\n",
    "像`JS`是可以生成器和`async`和`await`混用的，那`Python`呢？（NetCore不可以混用）\n",
    "```py\n",
    "import types\n",
    "\n",
    "# 和生成器完全分开了，不过可以理解为yield from\n",
    "@types.coroutine\n",
    "def get_value(value):\n",
    "    yield value\n",
    "\n",
    "async def get_name(name):\n",
    "    # 一系列逻辑处理\n",
    "    return await get_value(name)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    gen = get_name(\"小明\")\n",
    "    print(gen.send(None))\n",
    "# 直接混用会报错：TypeError: object generator can't be used in 'await' expression\n",
    "```\n",
    "\n",
    "我们的`async`和`await`虽然和`yield from`不是一个概念，但是可以理解为`yield from`上面这段代码你可以理解为：\n",
    "```py\n",
    "import types\n",
    "\n",
    "def get_value(value):\n",
    "    yield value\n",
    "\n",
    "# 这个async和await替换成yield from\n",
    "def get_name(name):\n",
    "    # 一系列逻辑处理\n",
    "    yield from get_value(name)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    gen = get_name(\"小明\")\n",
    "    print(gen.send(None))\n",
    "```\n",
    "PS：**Python默认和NetCore一样，不能直接混用，如果你一定要混用，那么得处理下**（`使用@asyncio.coroutine`也行）\n",
    "\n",
    "### 3.5.2.asyncio引入\n",
    "\n",
    "在今天之前，协程我们是这么实现的：`事件循环(loop)`+`回调(驱动生成器)`+`IO多路复用(epoll)`\n",
    "\n",
    "现在可以通过官方提供的`asyncio`（**可以理解为协程池**）来实现了（第三方还有一个`uvloop`【基于C写的`libuv`库（`nodejs`也是基于这个库）】）\n",
    "\n",
    "PS：`uvloop`的使用非常简单，只要在获取事件循环前将`asyncio`的事件循环策略设置为`uvloop`的:**`asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())`**\n",
    "\n",
    "#### 1.简单案例\n",
    "\n",
    "先看个简单的协程案例：\n",
    "```py\n",
    "import types\n",
    "import asyncio\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "async def test():\n",
    "    print(\"start...\")\n",
    "    # 不能再使用以前阻塞的暂停了\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"end...\")\n",
    "    return \"ok\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "    \n",
    "    # # >=python3.4\n",
    "    # # 返回asyncio的事件循环\n",
    "    # loop = asyncio.get_event_loop()\n",
    "    # # 运行事件循环，直到指定的future运行完毕，返回结果\n",
    "    # result = loop.run_until_complete(test())\n",
    "    # print(result)\n",
    "    \n",
    "    # python3.7\n",
    "    result = asyncio.run(test())\n",
    "    print(result)\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start...\n",
    "end...\n",
    "ok\n",
    "2.001772403717041\n",
    "```\n",
    "\n",
    "简单说下，`asyncio.run`是python3.7才简化出来的语法（类比NetCore的`Task.Run`）看看源码就知道了：\n",
    "```py\n",
    "# https://github.com/lotapp/cpython3/blob/master/Lib/asyncio/runners.py\n",
    "def run(main, *, debug=False):\n",
    "    # 以前是直接使用\"asyncio.get_event_loop()\"（开发人员一般都习惯这个了）\n",
    "    # 3.7开始推荐使用\"asyncio.get_running_loop()\"来获取正在运行的loop（获取不到就抛异常）\n",
    "    if events._get_running_loop() is not None:\n",
    "        raise RuntimeError(\"无法从正在运行的事件循环中调用asyncio.run()\")\n",
    "\n",
    "    if not coroutines.iscoroutine(main):\n",
    "        raise ValueError(\"{!r}应该是一个协程\".format(main))\n",
    "\n",
    "    loop = events.new_event_loop() # 创建一个新的事件循环\n",
    "    try:\n",
    "        events.set_event_loop(loop)  # 设置事件循环\n",
    "        loop.set_debug(debug)  # 是否调试运行（默认否）\n",
    "        return loop.run_until_complete(main)  # 等待运行\n",
    "    finally:\n",
    "        try:\n",
    "            _cancel_all_tasks(loop)  # 取消其他任务\n",
    "            loop.run_until_complete(loop.shutdown_asyncgens())\n",
    "        finally:\n",
    "            events.set_event_loop(None)\n",
    "            loop.close()\n",
    "```\n",
    "新版本其实就是使用了一个新的`loop`去启动`run_until_complete`\n",
    "\n",
    "PS：`uvloop`也可以这样去使用：获取loop`loop = uvloop.new_event_loop()`再替换原生的loop`asyncio.set_event_loop(loop)`\n",
    "\n",
    "### 3.5.3.批量任务\n",
    "\n",
    "#### 1.旧版本实现\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "async def test(i):\n",
    "    print(\"start...\")\n",
    "    # 不能再使用以前阻塞的暂停了\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"end...\")\n",
    "    return i\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    # # >=python3.4\n",
    "    loop = asyncio.get_event_loop()\n",
    "    # tasks = [asyncio.ensure_future(test(i)) for i in range(10)]\n",
    "    # 注意：是loop的方法，而不是asyncio的，不然就会引发RuntimeError：no running event loop\n",
    "    tasks = [loop.create_task(test(i)) for i in range(10)]\n",
    "    loop.run_until_complete(asyncio.wait(tasks))\n",
    "    for task in tasks:\n",
    "        print(task.result())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(tasks替换成这个也一样：`tasks = [asyncio.ensure_future(test(i)) for i in range(10)]`)\n",
    "```\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "0\n",
    "1\n",
    "2\n",
    "3\n",
    "4\n",
    "5\n",
    "6\n",
    "7\n",
    "8\n",
    "9\n",
    "2.028331995010376\n",
    "```\n",
    "\n",
    "然后我们再看看这个`asyncio.wait`是个啥：（回顾：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#wait()说明>）\n",
    "```\n",
    "# return_when 这个参数和之前一样\n",
    "FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED\n",
    "FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION\n",
    "ALL_COMPLETED = concurrent.futures.ALL_COMPLETED\n",
    "\n",
    "# 官方准备在未来版本废弃它的loop参数\n",
    "# 和concurrent.futures里面的wait不一样，这边是个协程\n",
    "async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):\n",
    "```\n",
    "\n",
    "**平时使用可以用高级API`asyncio.gather(*tasks)`来替换`asyncio.wait(tasks)`**\n",
    "\n",
    "#### 1.旧版另用\n",
    "\n",
    "PS：官方推荐使用`create_task的方式`来创建一个任务\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "async def test(i):\n",
    "    print(\"start...\")\n",
    "    # 不能再使用以前阻塞的暂停了\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"end...\")\n",
    "    return i\n",
    "\n",
    "async def main():\n",
    "    tasks = [test(i) for i in range(10)]\n",
    "    # await task 可以得到返回值（得到结果或者异常）\n",
    "    # for task in asyncio.as_completed(tasks):\n",
    "    #     try:\n",
    "    #         print(await task)\n",
    "    #     except Exception as ex:\n",
    "    #         print(ex)\n",
    "    return [await task for task in asyncio.as_completed(tasks)]\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    # old推荐使用\n",
    "    loop = asyncio.get_event_loop()\n",
    "    result_list = loop.run_until_complete(main())\n",
    "    print(result_list)\n",
    "    \n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(PS：用`asyncio.gather(*tasks)`直接替换`asyncio.wait(tasks)`也行)\n",
    "```\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "[1, 6, 4, 5, 0, 7, 8, 3, 2, 9]\n",
    "2.0242035388946533\n",
    "```\n",
    "\n",
    "**其实理解起来很简单，而且和`NetCore`以及`NodeJS`它们统一了，只要是`await xxx`就返回一个（`结果`|`异常`），`不await`就是一个`task对象`**\n",
    "\n",
    "#### 2.新版本实现\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "async def test(i):\n",
    "    print(\"start...\")\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"end...\")\n",
    "    return i\n",
    "\n",
    "async def main():\n",
    "    tasks = [test(i) for i in range(10)]\n",
    "    # 给`协程/futures`返回一个future聚合结果\n",
    "    return await asyncio.gather(*tasks) # 记得加*来解包\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    # python3.7\n",
    "    result_list = asyncio.run(main())\n",
    "    print(result_list)\n",
    "    \n",
    "    # 2.0259485244750977\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(语法简化太多了，用起来特别简单)\n",
    "```\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "2.00840163230896\n",
    "```\n",
    "\n",
    "关于参数需要加`*`解包的说明 ==> 看看函数定义就秒懂了：\n",
    "```py\n",
    "# 给 协程/futures 返回一个future聚合结果\n",
    "def gather(*coros_or_futures, loop=None, return_exceptions=False):\n",
    "    pass\n",
    "\n",
    "# 把协程或者awaitable对象包裹成task\n",
    "def ensure_future(coro_or_future, *, loop=None):\n",
    "    pass\n",
    "\n",
    "# 传入一个协程对象，返回一个task对象\n",
    "class BaseEventLoop(events.AbstractEventLoop):\n",
    "    def create_task(self, coro):\n",
    "        pass\n",
    "```\n",
    "\n",
    "### 关于高级和低级API的说明\n",
    "\n",
    "**asyncio的高级（`high-level`）API一般用于这几个方面**：（开发基本够用了）\n",
    "1. 并行运行Python协同程序并完全控制它们的执行\n",
    "2. **网络通信（`IO`）和进程间通信（`IPC`）**\n",
    "3. **子进程**（`subprocesses`）相关\n",
    "4. 通过**队列**（`Queue`）分配任务（`Tasks`）\n",
    "5. **同步**（`synchronize`）并发代码\n",
    "\n",
    "**低级（`low-level`）API一般这么用**：（事件循环和回调会用下，其他基本不用）\n",
    "1. 创建和管理**事件循环**，为网络、子进程、信号处理（`Signal`）等提供异步（`asynchronous `）API\n",
    "2. 为传输使用高效协议\n",
    "3. 使用`async/await`语法桥接基于**回调**的库和代码\n",
    "\n",
    "### 3.5.4.回调函数\n",
    "\n",
    "回调一般不利于代码维护，现在基本上是尽量不用了（异步代码用起来都和同步没多大差别了，回调也就没那么大用处了）\n",
    "\n",
    "#### 1.回调函数获取返回值\n",
    "\n",
    "上面说的获取返回值，其实也可以通过回调函数来获取：\n",
    "```py\n",
    "# 低级API示例\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get {url} ing\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "def call_back(task):\n",
    "    print(type(task))\n",
    "    print(task.result())\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.sogou.com\",\n",
    "        \"https://www.python.org\", \"https://www.asp.net\"\n",
    "    ]\n",
    "    tasks = set()  # 任务集合\n",
    "    loop = asyncio.get_event_loop()\n",
    "    for url in urls:\n",
    "        # task = asyncio.ensure_future(get_html(url))\n",
    "        task = loop.create_task(get_html(url))\n",
    "        # 设置回调函数\n",
    "        task.add_done_callback(call_back)\n",
    "        # 添加到任务集合中\n",
    "        tasks.add(task)\n",
    "    # 批量执行\n",
    "    loop.run_until_complete(asyncio.gather(*tasks))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（**`task.add_done_callback(回调函数)`**）\n",
    "```\n",
    "get https://www.baidu.com ing\n",
    "get https://www.sogou.com ing\n",
    "get https://www.python.org ing\n",
    "get https://www.asp.net ing\n",
    "<class '_asyncio.Task'>\n",
    "<h1>This is a test for https://www.baidu.com</h1>\n",
    "<class '_asyncio.Task'>\n",
    "<h1>This is a test for https://www.python.org</h1>\n",
    "<class '_asyncio.Task'>\n",
    "<h1>This is a test for https://www.sogou.com</h1>\n",
    "<class '_asyncio.Task'>\n",
    "<h1>This is a test for https://www.asp.net</h1>\n",
    "2.0168468952178955\n",
    "```\n",
    "\n",
    "#### 2.回调函数传参扩展\n",
    "\n",
    "实例：\n",
    "```py\n",
    "import asyncio\n",
    "import functools\n",
    "\n",
    "async def get_html(url):\n",
    "    await asyncio.sleep(2)\n",
    "    return \"This is a test for\"\n",
    "\n",
    "# 注意一个东西：通过偏函数传过来的参数在最前面\n",
    "def call_back(url, task):\n",
    "    # do something\n",
    "    print(type(task))\n",
    "    print(task.result(), url)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.sogou.com\",\n",
    "        \"https://www.python.org\", \"https://www.asp.net\"\n",
    "    ]\n",
    "    tasks = set()  # 任务集合\n",
    "    loop = asyncio.get_event_loop()\n",
    "    for url in urls:\n",
    "        # task = asyncio.ensure_future(get_html(url))\n",
    "        task = loop.create_task(get_html(url))\n",
    "        # 设置回调函数 （不支持传参数，我们就利用偏函数来传递）\n",
    "        task.add_done_callback(functools.partial(call_back, url))\n",
    "        # 添加到任务集合中\n",
    "        tasks.add(task)\n",
    "    # 批量执行\n",
    "    loop.run_until_complete(asyncio.gather(*tasks))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(**PS：通过偏函数传过来的参数在最前面**)\n",
    "```\n",
    "<class '_asyncio.Task'>\n",
    "This is a test for https://www.baidu.com\n",
    "<class '_asyncio.Task'>\n",
    "This is a test for https://www.python.org\n",
    "<class '_asyncio.Task'>\n",
    "This is a test for https://www.sogou.com\n",
    "<class '_asyncio.Task'>\n",
    "This is a test for https://www.asp.net\n",
    "2.0167236328125\n",
    "```\n",
    "\n",
    "### 3.5.5.异常相关\n",
    "\n",
    "之前说的`await task`可能得到结果也可能得到异常有些人可能还不明白 ==> 其实你把他看出同步代码（PS：协程的目的就是**像写同步代码一样进行异步编程**）就好理解了，函数执行要么得到结果要么得到返回值\n",
    "\n",
    "看个异常的案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get {url} ing\")\n",
    "    if url == \"https://www.asp.net\":\n",
    "        raise Exception(\"Exception is over\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "async def main():\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.asp.net\",\n",
    "        \"https://www.python.org\", \"https://www.sogou.com\"\n",
    "    ]\n",
    "    tasks = [get_html(url) for url in urls]\n",
    "    return await asyncio.gather(*tasks)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    try:\n",
    "        asyncio.run(main())\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "```\n",
    "输出：(**和同步代码没差别，可能出异常的部分加个异常捕获即可**)\n",
    "```\n",
    "get https://www.baidu.com ing\n",
    "get https://www.asp.net ing\n",
    "get https://www.python.org ing\n",
    "get https://www.sogou.com ing\n",
    "Exception is over\n",
    "0.008000373840332031\n",
    "```\n",
    "\n",
    "再一眼旧版怎么用：（PS：基本差不多，下次全部用新用法了）\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get {url} ing\")\n",
    "    if url == \"https://www.asp.net\":\n",
    "        raise Exception(\"Exception is over\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "async def main():\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.asp.net\",\n",
    "        \"https://www.python.org\", \"https://www.sogou.com\"\n",
    "    ]\n",
    "    tasks = set()  # 任务集合\n",
    "    tasks = [get_html(url) for url in urls]\n",
    "    return await asyncio.gather(*tasks)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    loop = asyncio.get_event_loop()\n",
    "    try:\n",
    "        # 批量执行\n",
    "        loop.run_until_complete(main())\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "\n",
    "### 常见异常\n",
    "\n",
    "**Python3调试过程中的常见异常**：<https://www.cnblogs.com/dotnetcrazy/p/9192089.html>\n",
    "\n",
    "#### asyncio中常见异常\n",
    "\n",
    "官方文档：`https://docs.python.org/3/library/asyncio-exceptions.html`\n",
    "1. **`asyncio.TimeoutError(Exception.Error)`：**\n",
    "    - 任务超时引发的异常\n",
    "2. **`asyncio.CancelledError(Exception.Error)`：**\n",
    "    - 任务取消引发的异常\n",
    "3. `asyncio.InvalidStateError(Exception.Error)`：\n",
    "    - `Task/Future`内部状态无效引发\n",
    "4. `asyncio.IncompleteReadError(Exception.Error)`：读取未完成引发的错误:\n",
    "    - 不完整: 在到达流结束之前读取字节字符串（读取了不完整的字符串就转换了）\n",
    "    - 不清楚读多少: 预期读取的字节总数未知\n",
    "5. `asyncio.LimitOverrunError(Exception)`：\n",
    "    - 超出缓冲区引发的异常\n",
    "6. `asyncio.SendfileNotAvailableError(Exception.ReferenceError.RuntimeError)`：\n",
    "    - 系统调用不适用于给定的套接字或文件类型（系统调用类型不匹配导致的）\n",
    "\n",
    "#### Python常见异常\n",
    "\n",
    "有些异常官方没有写进去，我补了一些常用的异常：`https://docs.python.org/3/library/exceptions.html`\n",
    "\n",
    "**`BaseException`**\n",
    "- `SystemExit`：`sys.exit()`引发的异常（目的：让Python解释器退出）\n",
    "- `KeyboardInterrupt`：用户Ctrl+C终止程序引发的异常\n",
    "- **`GeneratorExit`**：生成器或者协程关闭的时候产生的异常（**特别注意**）\n",
    "- **`Exception`**：所有内置异常（非系统退出）或者用户定义异常的基类\n",
    "    - **`asyncio.Error`**\n",
    "        - **`asyncio.CancelledError`**\n",
    "        - **`asyncio.TimeoutError`**：和`Exception.OSError.TimeoutError`区分开\n",
    "        - `asyncio.InvalidStateError`：`Task/Future`内部状态无效引发\n",
    "    - `asyncio.LimitOverrunError`：超出缓冲区引发的异常\n",
    "    - `StopIteration`：`next()、send()`引发的异常：\n",
    "        - `https://www.cnblogs.com/dotnetcrazy/p/9278573.html#6.Python迭代器`\n",
    "    - `StopAsyncIteration`：`__anext__()`引发的异常\n",
    "    - ArithmeticError\n",
    "        - FloatingPointError\n",
    "        - OverflowError\n",
    "        - ZeroDivisionError\n",
    "    - `AssertionError`：当断言`assert`语句失败时引发\n",
    "    - `AttributeError`：当属性引用或赋值失败时引发\n",
    "    - BufferError\n",
    "    - `EOFError`\n",
    "        - `asyncio.IncompleteReadError`：读取操作未完成引发的错误\n",
    "    - ImportError\n",
    "        - ModuleNotFoundError\n",
    "    - LookupError\n",
    "        - IndexError\n",
    "        - KeyError\n",
    "    - MemoryError\n",
    "    - NameError\n",
    "        - UnboundLocalError\n",
    "    - **`OSError`**：当系统函数返回与系统相关的错误时引发\n",
    "        - BlockingIOError\n",
    "        - ChildProcessError\n",
    "        - ConnectionError\n",
    "           - BrokenPipeError\n",
    "           - ConnectionAbortedError\n",
    "           - ConnectionRefusedError\n",
    "           - ConnectionResetError\n",
    "        - FileExistsError\n",
    "        - FileNotFoundError\n",
    "        - InterruptedError\n",
    "        - IsADirectoryError\n",
    "        - NotADirectoryError\n",
    "        - PermissionError\n",
    "        - ProcessLookupError\n",
    "        - **`TimeoutError`**：系统函数执行超时时触发\n",
    "    - `ReferenceError`：引用错误（对象被资源回收或者删除了）\n",
    "    - **`RuntimeError`**：出错了，但是检测不到错误类别时触发\n",
    "        - `NotImplementedError`：为实现报错（比如调用了某个不存在的子类方法）\n",
    "        - `RecursionError`：递归程度太深引发的异常\n",
    "        - `asyncio.SendfileNotAvailableError`：系统调用不适用于给定的套接字或文件类型\n",
    "    - **`SyntaxError`**：语法错误时引发（**粘贴代码经常遇到**）\n",
    "        - `IndentationError`：缩进有问题\n",
    "        - `TabError`：当缩进包含不一致的制表符和空格使用时引发\n",
    "    - SystemError\n",
    "    - `TypeError`：类型错误\n",
    "    - ValueError\n",
    "        - UnicodeError\n",
    "        - UnicodeDecodeError\n",
    "        - UnicodeEncodeError\n",
    "        - UnicodeTranslateError\n",
    "    - Warning\n",
    "    - DeprecationWarning\n",
    "    - PendingDeprecationWarning\n",
    "    - RuntimeWarning\n",
    "    - SyntaxWarning\n",
    "    - UserWarning\n",
    "    - FutureWarning\n",
    "    - ImportWarning\n",
    "    - UnicodeWarning\n",
    "    - BytesWarning\n",
    "    - ResourceWarning"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "### 新语法的说明\n",
    "\n",
    "Net方向的同志记得对比当时写的 <a href=\"https://mp.weixin.qq.com/s/PY1DZLiT74teuzh2GaA0kw\">Python3 与 C# 并发编程之～Net篇：https://www.cnblogs.com/dunitian/p/9419325.html</a>\n",
    "\n",
    "#### 1.概念\n",
    "\n",
    "先说说概念：\n",
    "1. `event_loop`事件循环：\n",
    "    - 程序开启一个无限的循环，程序员会把一些函数（协程）注册到事件循环上\n",
    "    - 当满足事件发生的时候，调用相应的协程函数\n",
    "2. `coroutine`协程：\n",
    "    - 协程对象，指一个使用`async`关键字定义的函数，它的调用不会立即执行函数，而是会返回一个协程对象\n",
    "    - 协程对象需要注册到事件循环，由事件循环调用\n",
    "3. `future`对象：\n",
    "    - 代表将来执行或没有执行的任务的结果（它和task上没有本质的区别）\n",
    "4. `task`任务：\n",
    "    - 一个协程对象就是一个原生可以挂起的函数，Task则是对协程进一步封装，其中包含任务的各种状态\n",
    "    - **`Task`对象是`Future`的子类**，它将`coroutine`和`Future`联系在一起，将`coroutine`封装成一个`Future`对象\n",
    "5. `async/await`关键字：\n",
    "    - 定义协程的关键字，`async`定义一个协程，`await`用于挂起阻塞的异步调用接口\n",
    "    - 类似于`yield from`（都是在调用方与子协程之间直接建立一个双向通道）\n",
    "    \n",
    "#### 2.语法\n",
    "\n",
    "**为了避免读者混乱于新旧代码的使用，从下面开始就直接使用最新的语法的**\n",
    "1. 运行asyncio：`asyncio.run(main())`\n",
    "    - 只运行一次(`if __name__ == \"__main__\"`)\n",
    "2. 创建一个任务：`asyncio.create_task(func())`\n",
    "    - Python3.8会多一个name的别名参数\n",
    "3. 批量执行任务：`asyncio.gather(*tasks)`\n",
    "    - return_exceptions=True可以屏蔽这批任务的异常，并把异常结果返回\n",
    "    - 如果有类似于(第一个任务完成|第一个异常产生后)进行相应的操作，则推荐`asyncio.wait`\n",
    "4. 获取loop：`asyncio.get_event_loop()`\n",
    "    - 优先考虑：`asyncio.get_running_loop()`（获取不到会抛异常）\n",
    "\n",
    "```py\n",
    "# 如果和旧版本混用，就应该这么写了（麻烦）\n",
    "try:\n",
    "    loop = asyncio.get_running_loop()\n",
    "except RuntimeError as ex:\n",
    "    print(ex) # no running event loop\n",
    "    loop = asyncio.get_event_loop()\n",
    "...\n",
    "loop.run_until_complete(xxx)\n",
    "```\n",
    "\n",
    "新语法：\n",
    "```py\n",
    "async def main():\n",
    "    loop = asyncio.get_running_loop()\n",
    "    ...\n",
    "\n",
    "asyncio.run(main())\n",
    "```\n",
    "\n",
    "#### 3.状态\n",
    "\n",
    "Task基本上就是这几个状态（生成器、Future也是）：\n",
    "1. `Pending`：创建Task，还未执行\n",
    "2. `Running`：事件循环正在调用执行任务\n",
    "3. `Done`：Task执行完毕\n",
    "4. `Cancelled`：Task被取消后的状态\n",
    "\n",
    "#### 4.时序图\n",
    "\n",
    "Python3.7之前官方贴了张时序图，我们拿来理解上面的话：`https://docs.python.org/3.6/library/asyncio-task.html`\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def compute(x, y):\n",
    "    print(f\"计算 {x}+{y}...\")\n",
    "    await asyncio.sleep(1.0)\n",
    "    return x + y\n",
    "\n",
    "async def main(x, y):\n",
    "    result = await compute(x, y)\n",
    "    print(f\"{x}+{y}={result}\")\n",
    "\n",
    "loop = asyncio.get_event_loop()\n",
    "loop.run_until_complete(main(1, 2))\n",
    "loop.close()\n",
    "```\n",
    "![8.时序.png](https://img2018.cnblogs.com/blog/1127869/201901/1127869-20190109223454952-805317243.png)\n",
    "\n",
    "### 3.5.4.回调函数（新用法）\n",
    "\n",
    "和旧版本比起来其实就是创建一个`task`，然后为`task`添加一个回调函数`add_done_callback`\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get {url} ing\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "def callback_func(task):\n",
    "    print(type(task))\n",
    "    if task.done():\n",
    "        print(f\"done\")  # print(task.result())\n",
    "\n",
    "async def main():\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.asp.net\",\n",
    "        \"https://www.python.org\", \"https://www.sogou.com\"\n",
    "    ]\n",
    "    # asyncio.create_task来创建一个Task\n",
    "    tasks = [asyncio.create_task(get_html(url)) for url in urls]\n",
    "    # 给每个任务都加一个回调函数\n",
    "    for task in tasks:\n",
    "        task.add_done_callback(callback_func)\n",
    "    # 批量执行任务\n",
    "    result = await asyncio.gather(*tasks)\n",
    "    print(result)  # 返回 result list\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "get https://www.baidu.com ing\n",
    "get https://www.asp.net ing\n",
    "get https://www.python.org ing\n",
    "get https://www.sogou.com ing\n",
    "<class '_asyncio.Task'>\n",
    "done\n",
    "<class '_asyncio.Task'>\n",
    "done\n",
    "<class '_asyncio.Task'>\n",
    "done\n",
    "<class '_asyncio.Task'>\n",
    "done\n",
    "['<h1>This is a test for https://www.baidu.com</h1>', '<h1>This is a test for https://www.asp.net</h1>', '<h1>This is a test for https://www.python.org</h1>', '<h1>This is a test for https://www.sogou.com</h1>']\n",
    "2.0189685821533203\n",
    "```\n",
    "\n",
    "注意：<a href=\"https://docs.python.org/3.8/library/asyncio-eventloop.html#asyncio.loop.add_signal_handler\">`add_signal_handler`是loop独有的方法，Task中没有</a>，eg：`loop.add_signal_handler(signal.SIGINT, callback_handle, *args)`\n",
    "\n",
    "### 3.5.5.异常相关扩展\n",
    "\n",
    "关于批量任务的异常处理：\n",
    "1. 默认：同一批次有一个task产生了异常，这一批次任务就全部结束了\n",
    "2. `return_exceptions=True`:不影响其他任务，异常消息也放在结果列表中\n",
    "3. 当`gather`被取消的时候，不管True or False，这批次任务全部取消\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get {url} ing\")\n",
    "    if url == \"https://www.asp.net\":\n",
    "        raise Exception(\"Exception is over\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "def callback_func(task):\n",
    "    if task.done():\n",
    "        print(f\"done\")  # print(task.result())\n",
    "\n",
    "async def main():\n",
    "    urls = [\n",
    "        \"https://www.baidu.com\", \"https://www.asp.net\",\n",
    "        \"https://www.python.org\", \"https://www.sogou.com\"\n",
    "    ]\n",
    "    # asyncio.create_task来创建一个Task\n",
    "    tasks = [asyncio.create_task(get_html(url)) for url in urls]\n",
    "    # 给每个任务都加一个回调函数\n",
    "    for task in tasks:\n",
    "        task.add_done_callback(callback_func)\n",
    "    # 批量执行任务\n",
    "    result = await asyncio.gather(*tasks, return_exceptions=True)\n",
    "    print(result)  # 返回 result list\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "get https://www.baidu.com ing\n",
    "get https://www.asp.net ing\n",
    "get https://www.python.org ing\n",
    "get https://www.sogou.com ing\n",
    "done\n",
    "done\n",
    "done\n",
    "done\n",
    "['<h1>This is a test for https://www.baidu.com</h1>', Exception('Exception is over'), '<h1>This is a test for https://www.python.org</h1>', '<h1>This is a test for https://www.sogou.com</h1>']\n",
    "2.013272523880005\n",
    "```\n",
    "\n",
    "### 3.5.6.任务分组、取消\n",
    "\n",
    "#### 1.分组\n",
    "\n",
    "看个简单的任务分组案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get url for{url}\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "async def main():\n",
    "    urls1 = [\"https://www.baidu.com\", \"https://www.asp.net\"]\n",
    "    urls2 = [\"https://www.python.org\", \"https://www.sogou.com\"]\n",
    "\n",
    "    tasks1 = [asyncio.create_task(get_html(url)) for url in urls1]\n",
    "    tasks2 = [asyncio.create_task(get_html(url)) for url in urls2]\n",
    "    \n",
    "    # 等待两组都完成，然后返回聚合结果\n",
    "    result = await asyncio.gather(*tasks1, *tasks2)\n",
    "    print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    try:\n",
    "        asyncio.run(main())\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "```\n",
    "输出：(两个分组结果被一起放到了list中)\n",
    "```\n",
    "get url forhttps://www.baidu.com\n",
    "get url forhttps://www.asp.net\n",
    "get url forhttps://www.python.org\n",
    "get url forhttps://www.sogou.com\n",
    "['<h1>This is a test for https://www.baidu.com</h1>', '<h1>This is a test for https://www.asp.net</h1>', '<h1>This is a test for https://www.python.org</h1>', '<h1>This is a test for https://www.sogou.com</h1>']\n",
    "2.0099380016326904\n",
    "```\n",
    "\n",
    "#### 2.取消\n",
    "\n",
    "如果想要对`Group1`和`Group2`进行更多的自定化，可以再包裹一层`gather`方法：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(url):\n",
    "    print(f\"get url for{url}\")\n",
    "    await asyncio.sleep(2)\n",
    "    return f\"<h1>This is a test for {url}</h1>\"\n",
    "\n",
    "async def main():\n",
    "    urls1 = [\"https://www.baidu.com\", \"https://www.asp.net\"]\n",
    "    urls2 = [\"https://www.python.org\", \"https://www.sogou.com\"]\n",
    "\n",
    "    tasks1 = [asyncio.create_task(get_html(url)) for url in urls1]\n",
    "    tasks2 = [asyncio.create_task(get_html(url)) for url in urls2]\n",
    "\n",
    "    group1 = asyncio.gather(*tasks1)\n",
    "    group2 = asyncio.gather(*tasks2)\n",
    "    \n",
    "    # 分组2因为某原因被取消任务了（模拟）\n",
    "    group2.cancel()\n",
    "\n",
    "    # 等待两组都完成，然后返回聚合结果\n",
    "    result = await asyncio.gather(group1, group2, return_exceptions=True)\n",
    "    print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    try:\n",
    "        asyncio.run(main())\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "get url forhttps://www.baidu.com\n",
    "get url forhttps://www.asp.net\n",
    "[['<h1>This is a test for https://www.baidu.com</h1>', '<h1>This is a test for https://www.asp.net</h1>'], CancelledError()]\n",
    "2.0090348720550537\n",
    "```\n",
    "\n",
    "再看个单个任务的案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def test():\n",
    "    print(\"start...\")\n",
    "    await asyncio.sleep(10)\n",
    "    print(\"end...\")\n",
    "\n",
    "async def main():\n",
    "    task = asyncio.create_task(test())\n",
    "\n",
    "    await asyncio.sleep(1)\n",
    "\n",
    "    # 取消task任务\n",
    "    task.cancel()\n",
    "\n",
    "    try:\n",
    "        await task\n",
    "    except asyncio.CancelledError:\n",
    "        print(f\"任务已经被取消：{task.cancelled()}\")\n",
    "        print(f\"任务是因为异常而完成：{task.done()}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start...\n",
    "任务已经被取消：True\n",
    "任务是因为异常而完成：True\n",
    "1.0133979320526123\n",
    "```\n",
    "\n",
    "简单说明下：\n",
    "1. `task.done()`：任务是否完成\n",
    "    - 任务完成：`task.done() ==> true`：\n",
    "        1. 任务正常完成\n",
    "        2. 触发异常而被标记为任务完成\n",
    "2. `task.cancelled()`：用来判断是否成功取消\n",
    "\n",
    "为什么这么说？看看源码：\n",
    "```py\n",
    "# 完成包含了正常+异常\n",
    "if outer.done():\n",
    "    # 把因为异常完成的任务打个标记\n",
    "    if not fut.cancelled():\n",
    "        fut.exception() # 标记检索的异常\n",
    "```\n",
    "\n",
    "PS：官方推荐**`asyncio.all_tasks`**(loop中尚未完成的Task集合):\n",
    "- 原来是通过：`asyncio.Task.all_tasks`来获取(返回loop的所有Task集合)\n",
    "\n",
    "### wait_for and wait\n",
    "\n",
    "#### 1.一个任务限时等待(wait_for)\n",
    "\n",
    "超时等待：**`asyncio.wait_for(task, timeout)`**\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def test(time):\n",
    "    print(\"start...\")\n",
    "    await asyncio.sleep(time)\n",
    "    print(\"end...\")\n",
    "    return time\n",
    "\n",
    "async def main():\n",
    "    task = asyncio.create_task(test(3))\n",
    "    try:\n",
    "        result = await asyncio.wait_for(task, timeout=2)\n",
    "        print(result)\n",
    "    except asyncio.CancelledError:\n",
    "        print(\"Cancel\")\n",
    "    except asyncio.TimeoutError:\n",
    "        print(\"超时取消\")\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start...\n",
    "超时取消\n",
    "2.007002115249634\n",
    "```\n",
    "\n",
    "#### 2.多个任务限时等待(wait)\n",
    "\n",
    "`wait`是比`gather`更底层的api，比如现在这个**多任务限时等待**`gather`并不能满足:\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def test(time):\n",
    "    print(\"start...\")\n",
    "    await asyncio.sleep(time)\n",
    "    print(\"end...\")\n",
    "    return time\n",
    "\n",
    "async def main():\n",
    "    tasks = [asyncio.create_task(test(i)) for i in range(10)]\n",
    "\n",
    "    # 已完成的任务（包含异常），未完成的任务\n",
    "    done, pending = await asyncio.wait(tasks, timeout=2)\n",
    "    # 任务总数（我用了3种表示）PS：`all_tasks()`的时候记得去除main的那个\n",
    "    print(\n",
    "        f\"任务总数：{len(tasks)}=={len(done)+len(pending)}=={len(asyncio.Task.all_tasks())-1}\"\n",
    "    )\n",
    "    # 所有未完成的task：asyncio.all_tasks()，记得去掉run(main())\n",
    "    print(f\"未完成Task:{len(pending)}=={len(asyncio.all_tasks()) - 1}\")\n",
    "\n",
    "    print(await asyncio.gather(*done))\n",
    "    # for task in done:\n",
    "        # print(await task)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "start...\n",
    "end...\n",
    "end...\n",
    "end...\n",
    "任务总数：10==10==10\n",
    "未完成Task:7==7\n",
    "[0, 1, 2]\n",
    "2.0071778297424316\n",
    "```\n",
    "\n",
    "#### wait的扩展\n",
    "\n",
    "用法其实和Future一样（<a href=\"https://mp.weixin.qq.com/s/UeBOJlXwKc24zwSD2-bzWw\">https://www.cnblogs.com/dotnetcrazy/p/9528315.html#Future对象</a>），这边就当再普及下新语法了\n",
    "\n",
    "##### 第一个任务执行完成则结束此批次任务\n",
    "\n",
    "项目里经常有这么一个场景：`同时调用多个同效果的API，有一个返回后取消其他请求`,看个引入案例\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def test(i):\n",
    "    print(f\"start...task{i}\")\n",
    "    await asyncio.sleep(i)\n",
    "    print(f\"end...task{i}\")\n",
    "    return \"ok\"\n",
    "\n",
    "# 第一个任务执行完成则结束此批次任务\n",
    "async def main():\n",
    "    tasks = [asyncio.create_task(test(i)) for i in range(10)]\n",
    "    \n",
    "    # 项目里经常有这么一个场景：同时调用多个同效果的API，有一个返回后取消其他请求\n",
    "    done, pending = await asyncio.wait(\n",
    "        tasks, return_when=asyncio.FIRST_COMPLETED)\n",
    "\n",
    "    # print(await asyncio.gather(*done))\n",
    "    for task in done:\n",
    "        print(await task)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start...task0\n",
    "start...task1\n",
    "start...task2\n",
    "start...task3\n",
    "start...task4\n",
    "start...task5\n",
    "start...task6\n",
    "start...task7\n",
    "start...task8\n",
    "start...task9\n",
    "end...task0\n",
    "ok\n",
    "0.017002105712890625\n",
    "```\n",
    "\n",
    "课后拓展：(**`asyncio.shield`保护等待对象不被取消**)\n",
    "https://docs.python.org/3/library/asyncio-task.html#shielding-from-cancellation\n",
    "\n",
    "**下级预估：旧代码兼容、同步语、Socket新用**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "### 代码答疑\n",
    "\n",
    "之前有人问我，这个`asyncio.get_running_loop()`到底是用还是不用？为什么一会`asyncio.get_event_loop()`一会又是`asyncio.get_running_loop()`，一会是`loop.run_until_complete()`一会又是`asyncio.run()`的，有点混乱了。\n",
    "\n",
    "之前逆天简单的提了一下，可能说的还是不太详细，这边再举几个例子说说：\n",
    "\n",
    "首先：如果你用的是**`Python3.7`之前的版本，那么你用不到`loop = asyncio.get_running_loop()`和`asyncio.run()`的**\n",
    "\n",
    "如果是**老版本**你就使用`asyncio.get_event_loop()`来获取`loop`，用`loop.run_until_complete()`来运行：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def test():\n",
    "    print(\"start ...\")\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"end ...\")\n",
    "\n",
    "# 如果你用`get_running_loop`就不要和`loop.run_until_complete`混用\n",
    "loop = asyncio.get_event_loop()\n",
    "loop.run_until_complete(test())\n",
    "```\n",
    "输出：（混用需要捕获Runtime的异常）\n",
    "```\n",
    "start ...\n",
    "end ...\n",
    "```\n",
    "上节课说使用`asyncio.get_running_loop()`麻烦的情景是这个：（这种情况倒不如直接`asyncio.get_event_loop()`获取loop了）\n",
    "```py\n",
    "# 如果和旧版本混用，就应该这么写了（麻烦）\n",
    "try:\n",
    "    loop = asyncio.get_running_loop()\n",
    "except RuntimeError as ex:\n",
    "    loop = asyncio.get_event_loop()\n",
    "...\n",
    "asyncio.run(test())\n",
    "```\n",
    "\n",
    "官方推荐的新语法是这样的：(>=`Python3.7`)\n",
    "```py\n",
    "async def main():\n",
    "    loop = asyncio.get_running_loop()\n",
    "    ...\n",
    "\n",
    "asyncio.run(main())\n",
    "```\n",
    "PS：记住一句就行：**`asyncio.get_running_loop()`和`asyncio.run()`成对出现**\n",
    "\n",
    "可以这么理解：`asyncio.run`里会创建对应的`loop`，所以你才能获取正在运行的`loop`：\n",
    "```py\n",
    "# https://github.com/lotapp/cpython3/blob/master/Lib/asyncio/runners.py\n",
    "def run(main, *, debug=False):\n",
    "    if events._get_running_loop() is not None:\n",
    "        raise RuntimeError(\"无法从正在运行的事件循环中调用asyncio.run()\")\n",
    "\n",
    "    if not coroutines.iscoroutine(main):\n",
    "        raise ValueError(\"{!r}应该是一个协程\".format(main))\n",
    "    \n",
    "    # 创建一个新的事件循环\n",
    "    loop = events.new_event_loop()\n",
    "    try:\n",
    "        events.set_event_loop(loop) # 设置事件循环\n",
    "        loop.set_debug(debug) # 是否调试运行（默认否）\n",
    "        return loop.run_until_complete(main) # 等待运行\n",
    "    finally:\n",
    "        try:\n",
    "            _cancel_all_tasks(loop) # 取消其他任务\n",
    "            loop.run_until_complete(loop.shutdown_asyncgens())\n",
    "        finally:\n",
    "            events.set_event_loop(None)\n",
    "            loop.close()\n",
    "```\n",
    "\n",
    "**就是怕大家混乱，上节课开始就直接使用的最新语法，旧语法文章里尽量不使用了，本节也是**\n",
    "\n",
    "### 3.5.7.兼容旧代码 or 运行阻塞代码\n",
    "\n",
    "部分可以参考官方文档：`https://docs.python.org/3/library/asyncio-eventloop.html`\n",
    "\n",
    "学了协程`GIL`的问题其实也不是多大的事情了，多进程+协程就可以了，`asyncio`现在也提供了线程安全的`run`方法：**`asyncio.run_coroutine_threadsafe(coro)`**（也算是对GIL给出的官方解决方法了）\n",
    "\n",
    "#### 1.协程 and 线程池\n",
    "\n",
    "前面我们说过了并发编程（线程+进程）的通用解决方案：<a href=\"https://mp.weixin.qq.com/s/UeBOJlXwKc24zwSD2-bzWw\" target=\"_blank\">并发编程：concurrent.futures专栏</a>\n",
    "\n",
    "`asyncio`框架虽然几乎包含了所有常用功能，但毕竟是新事物，旧代码怎么办？协程只是单线程工作，理论上不能使用阻塞代码，那库或者api只能提供阻塞的调用方式怎么办？ ~ 不用慌，可以使用官方提供的兼容方法，先看个案例：\n",
    "\n",
    "##### 1.回顾下一起的通用方案：\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "import concurrent.futures\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "def test(n):\n",
    "    return sum(i * i for i in range(10**n))\n",
    "\n",
    "# old main\n",
    "def main():\n",
    "    with concurrent.futures.ThreadPoolExecutor() as pool:\n",
    "        # 注意：future和asyncio.future是不一样的\n",
    "        future = pool.submit(test, 7)\n",
    "        result = future.result()\n",
    "        print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    main()  # old\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（注意：`future`和`asyncio.future`不是一个东西，只是类似而已）\n",
    "```\n",
    "333333283333335000000\n",
    "15.230607032775879\n",
    "```\n",
    "##### 2.兼容版新用法：\n",
    "\n",
    "```py\n",
    "import asyncio\n",
    "import concurrent.futures\n",
    "\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "def test(n):\n",
    "    return sum(i * i for i in range(10**n))\n",
    "\n",
    "async def main():\n",
    "    # 获取loop\n",
    "    loop = asyncio.get_running_loop()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as pool:\n",
    "        # 新版兼任代码\n",
    "        result = await loop.run_in_executor(pool, test, 7)\n",
    "        print(result)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())  # new\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（不谈其他的，至少运行速度快了）\n",
    "```\n",
    "333333283333335000000\n",
    "15.283994913101196\n",
    "```\n",
    "\n",
    "##### 源码分析\n",
    "\n",
    "我们来看看`run_in_executor`的内部逻辑是啥：\n",
    "```py\n",
    "class BaseEventLoop(events.AbstractEventLoop):\n",
    "    def run_in_executor(self, executor, func, *args):\n",
    "        # 检查loop是否关闭，如果关闭就抛`RuntimeError`异常\n",
    "        self._check_closed()\n",
    "        if self._debug:\n",
    "            self._check_callback(func, 'run_in_executor')\n",
    "        # 如果不传一个executor,就会使用默认的executor\n",
    "        # 换句话说：你可以不传`线程池`\n",
    "        if executor is None:\n",
    "            executor = self._default_executor\n",
    "            if executor is None:\n",
    "                executor = concurrent.futures.ThreadPoolExecutor()\n",
    "                self._default_executor = executor\n",
    "        # 把`concurrent.futures.Future`对象封装成`asyncio.futures.Future`对象\n",
    "        return futures.wrap_future(executor.submit(func, *args), loop=self)\n",
    "```\n",
    "看完源码就发现，代码还可以进一步简化：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 模拟一个耗时操作\n",
    "def test(n):\n",
    "    return sum(i * i for i in range(10**n))\n",
    "\n",
    "async def main():\n",
    "    # 获取loop\n",
    "    loop = asyncio.get_running_loop()\n",
    "\n",
    "    # 新版兼任代码\n",
    "    result = await loop.run_in_executor(None, test, 7)\n",
    "    print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "333333283333335000000\n",
    "15.367998838424683\n",
    "```\n",
    "\n",
    "**PS：协程里面不应该出现传统的阻塞代码，如果只能用那些代码，那么这个就是一个兼任的措施了**\n",
    "\n",
    "#### 2.回调扩展\n",
    "\n",
    "这个没有之前讲的那些常用，就当了解下，框架里面碰到不至于懵逼：\n",
    "1. Task执行完后执行：**`add_done_callback(回调函数)`**\n",
    "    - **`task.add_done_callback()`** or `loop.add_done_callback()`\n",
    "    - 想要传参数可以使用：`functools.partial(call_back, url)`\n",
    "    - PS：通过偏函数传过来的参数在最前面：`call_back(url,task)`\n",
    "2. 尽快执行：**`call_soon(callback,*args)`**\n",
    "    - `loop.call_soon()`、线程安全：`loop.call_soon_threadsafe()`\n",
    "    - 可以看成是`loop.call_later(0,callback,*args)`\n",
    "    - 一般临时插入一个任务的时候会用到\n",
    "3. 指定时间后执行：**`loop.call_later(delay,callback,*args)`**\n",
    "    - 延迟可以是int或float，以秒为单位（相对于当前时间）\n",
    "    - 返回的对象可以使用cancel()方法来取消任务\n",
    "4. 指定协程时间后执行：**`loop.call_at(绝对时间,callback,*args)`**\n",
    "    - 和call_later差不多，时间使用绝对时间(这个绝对时间是loop的time()方法)\n",
    "\n",
    "注意点：**首先要保证任务执行前loop不断开**，比如你`call_later(2,xxx)`，这时候loop退出了，那么任务肯定完成不了\n",
    "\n",
    "这个比较简单，看个案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "def test(name):\n",
    "    print(f\"start {name}...\")\n",
    "    print(f\"end {name}...\")\n",
    "\n",
    "async def main():\n",
    "    # 正在执行某个任务\n",
    "    loop = asyncio.get_running_loop()\n",
    "\n",
    "    # 插入一个更要紧的任务\n",
    "    # loop.call_later(0, callback, *args)\n",
    "    task1 = loop.call_soon(test, \"task1\")\n",
    "\n",
    "    # 多少秒后执行\n",
    "    task2 = loop.call_later(2, test, \"task2\")\n",
    "\n",
    "    # 内部时钟时间\n",
    "    task3 = loop.call_at(loop.time() + 3, test, \"task3\")\n",
    "\n",
    "    print(type(task1))\n",
    "    print(type(task2))\n",
    "    print(type(task3))\n",
    "\n",
    "    # 保证loop在执行完毕后才关闭\n",
    "    await asyncio.sleep(5)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(`回调函数一般都是普通函数`)\n",
    "```\n",
    "<class 'asyncio.events.Handle'>\n",
    "<class 'asyncio.events.TimerHandle'>\n",
    "<class 'asyncio.events.TimerHandle'>\n",
    "start task1...\n",
    "end task1...\n",
    "start task2...\n",
    "end task2...\n",
    "start task3...\n",
    "end task3...\n",
    "4.9966819286346436\n",
    "```\n",
    "\n",
    "PS：关于返回值的说明可以看官方文档：`https://docs.python.org/3/library/asyncio-eventloop.html#callback-handles`\n",
    "\n",
    "然后说下**`call_later`**（这个执行过程会**按照时间排个先后顺序**，然后再批次运行）\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 回调函数一般都是普通函数\n",
    "def test(name):\n",
    "    print(name)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    loop = asyncio.get_event_loop()\n",
    "\n",
    "    # 新版本限制了时间不能超过24h（防止有些人当定时任务来乱用）\n",
    "    # 这个执行过程会安装时间排个先后顺序，然后再批次运行\n",
    "    task4 = loop.call_later(4, test, \"task2-4\")\n",
    "    task2 = loop.call_later(2, test, \"task2-2\")\n",
    "    task3 = loop.call_later(3, test, \"task2-3\")\n",
    "    task1 = loop.call_later(1, test, \"task2-1\")\n",
    "    # 取消测试\n",
    "    task4.cancel()\n",
    "    # close是直接丢弃任务然后关闭loop\n",
    "    loop.call_later(4, loop.stop)  # 等任务执行完成结束任务 loop.stop()\n",
    "\n",
    "    # run内部运行的是run_until_complete，而run_until_complete内部运行的是run_forever\n",
    "    loop.run_forever()\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（`asyncio.get_running_loop()`不要和旧代码混用）\n",
    "```\n",
    "task2-1\n",
    "task2-2\n",
    "task2-3\n",
    "4.009201526641846\n",
    "```\n",
    "**PS：`run`内部运行的是`run_until_complete`，而`run_until_complete`内部运行的是`run_forever`**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "### Task答疑\n",
    "\n",
    "从开始说新语法之后，我们创建任务都直接用`asyncio.create_task`来包裹一层，有人问我这个`Task`除了是`Future`的子类外，有啥用？为啥不直接使用`Future`呢？貌似也没语法啊？\n",
    "\n",
    "看一个案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 不是协程就加个装饰器\n",
    "@asyncio.coroutine\n",
    "def test():\n",
    "    print(\"this is a test\")\n",
    "\n",
    "async def test_async():\n",
    "    print(\"this is a async test\")\n",
    "    await asyncio.sleep(1)\n",
    "\n",
    "async def main():\n",
    "    # 传入一个协程对象，返回一个task\n",
    "    task1 = asyncio.create_task(test())\n",
    "    task2 = asyncio.create_task(test_async())\n",
    "    await asyncio.gather(task1, task2)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "this is a test\n",
    "this is a async test\n",
    "1.0070011615753174\n",
    "```\n",
    "我们来看看`asyncio.create_task`的源码：（关键在`Task`类）\n",
    "```py\n",
    "# 传入一个协程对象，返回一个Task对象\n",
    "def create_task(self, coro):\n",
    "    self._check_closed()\n",
    "    if self._task_factory is None:\n",
    "        # look：核心点\n",
    "        task = tasks.Task(coro, loop=self)\n",
    "        if task._source_traceback:\n",
    "            del task._source_traceback[-1]\n",
    "    else:\n",
    "        task = self._task_factory(self, coro)\n",
    "    return task\n",
    "```\n",
    "看看核心类`Task`：\n",
    "```py\n",
    "class Task(futures._PyFuture):\n",
    "    def __init__(self, coro, *, loop=None):\n",
    "        super().__init__(loop=loop)\n",
    "        ...\n",
    "        # 安排了一个尽快执行的回调方法：self.__step\n",
    "        self._loop.call_soon(self.__step, context=self._context)\n",
    "        \n",
    "    def __step(self, exc=None):\n",
    "       try:\n",
    "            if exc is None:\n",
    "                # 协程初始化（生成器或者协程初始化 next(xxx））\n",
    "                result = coro.send(None)\n",
    "            else:\n",
    "                result = coro.throw(exc)\n",
    "        except StopIteration as exc:\n",
    "            if self._must_cancel:\n",
    "                # 在停止之前取消任务\n",
    "                self._must_cancel = False\n",
    "                super().set_exception(futures.CancelledError())\n",
    "            else:\n",
    "                # 拿到了协程/生成器的结果\n",
    "                super().set_result(exc.value)\n",
    "        except futures.CancelledError:\n",
    "            super().cancel()  # I.e., Future.cancel(self).\n",
    "        except Exception as exc:\n",
    "            super().set_exception(exc)\n",
    "        except BaseException as exc:\n",
    "            super().set_exception(exc)\n",
    "            raise\n",
    "    ...\n",
    "```\n",
    "\n",
    "PS：那么很**明显了，`Task`的作用就类似于`future`和`协程`的中间人了**（屏蔽某些差异）\n",
    "\n",
    "### 3.5.8.Socket新用法\n",
    "\n",
    "官方文档：https://docs.python.org/3/library/asyncio-stream.html\n",
    "\n",
    "`asyncio`实现了`TCP、UDP、SSL`等协议，`aiohttp`则是基于`asyncio`实现的HTTP框架，我们简单演示一下（PS：网络通信基本上都是使用`aiohttp`）\n",
    "\n",
    "#### 1.简单案例\n",
    "\n",
    "服务端：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def handler(client_reader, client_writer):\n",
    "    # 没有数据就阻塞等（主线程做其他事情去了）\n",
    "    data = await client_reader.read(2048)\n",
    "    print(data.decode(\"utf-8\"))\n",
    "    \n",
    "    client_writer.write(\"骊山语罢清宵半,泪雨霖铃终不怨\\n何如薄幸锦衣郎,比翼连枝当日愿\".encode(\"utf-8\"))\n",
    "    await client_writer.drain()  # 等待缓冲区（缓冲区没占满就直接返回）\n",
    "    client_writer.close()  # 关闭连接\n",
    "\n",
    "async def main():\n",
    "    server = await asyncio.start_server(handler, \"127.0.0.1\", 8080)\n",
    "    print(\"Server已经启动，端口：8080\")\n",
    "    # 实现了协程方法`__aenter__`和`__aexit__`的可以使用`async with`\n",
    "    async with server:\n",
    "        # async def serve_forever(self):pass ==> use await\n",
    "        await server.serve_forever()  # 异步方法\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "客户端：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def main():\n",
    "    reader, writer = await asyncio.open_connection(\"127.0.0.1\", 8080)\n",
    "    writer.write(\"人生若只如初见,何事秋风悲画扇\\n等闲变却故人心,却道故人心易变\".encode(\"utf-8\"))\n",
    "    data = await reader.read(2048)\n",
    "    if data:\n",
    "        print(data.decode(\"utf-8\"))\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出图示：\n",
    "![9.conn.png](https://img2018.cnblogs.com/blog/1127869/201901/1127869-20190121140913762-306458267.png)\n",
    "\n",
    "#### 2.HTTP案例\n",
    "\n",
    "再举个HTTP的案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def get_html(host):\n",
    "    print(\"get_html %s...\" % host)\n",
    "    reader, writer = await asyncio.open_connection(host, 80)\n",
    "    writer.write(f\"GET / HTTP/1.1\\r\\nHost: {host}\\r\\n\\r\\n\".encode('utf-8'))\n",
    "    await writer.drain()  # 等待缓冲区\n",
    "\n",
    "    html_list = []\n",
    "    async for line in reader:\n",
    "        html_list.append(line.decode(\"utf-8\"))\n",
    "\n",
    "    writer.close()  # 关闭连接\n",
    "    return \"\\n\".join(html_list)\n",
    "\n",
    "async def main():\n",
    "    tasks = [\n",
    "        asyncio.create_task(get_html(url))\n",
    "        for url in ['dotnetcrazy.cnblogs.com', 'dunitian.cnblogs.com']\n",
    "    ]\n",
    "    html_list = await asyncio.gather(*tasks)\n",
    "    print(html_list)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "get_html dotnetcrazy.cnblogs.com...\n",
    "get_html dunitian.cnblogs.com...\n",
    "[html内容省略,html内容省略]\n",
    "5.092018604278564\n",
    "```\n",
    "\n",
    "GIF过程图：\n",
    "![10.过程.gif](https://img2018.cnblogs.com/blog/1127869/201901/1127869-20190121163455314-5441844.gif)\n",
    "\n",
    "PS：（后面会继续说的）\n",
    "1. **实现了协程方法`__anext__`的可以使用`async for`**\n",
    "2. **实现了协程方法`__aenter__`和`__aexit__`的可以使用`async with`**\n",
    "\n",
    "#### 3.源码分析\n",
    "\n",
    "还记得之前IO多路复用的时候自己写的`非阻塞Server`不，简单梳理下流程，然后咱们再一起看看`asyncio`对应的源码：\n",
    "1. 设置`Socket`为非阻塞（**`socket.setblocking(False)`**）\n",
    "2. 利用轮询用来监视文件描述符`fd`（**`register`**）\n",
    "3. 对可读写的`socket`进行相应操作\n",
    "4. 取消轮询的监听（**`unregister`**）\n",
    "\n",
    "看看`await asyncio.open_connection(ip,port)`的源码：\n",
    "```py\n",
    "# asyncio.streams.py\n",
    "async def open_connection(host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds):\n",
    "    if loop is None:\n",
    "        loop = events.get_event_loop()\n",
    "    reader = StreamReader(limit=limit, loop=loop)\n",
    "    protocol = StreamReaderProtocol(reader, loop=loop)\n",
    "    # 核心点\n",
    "    transport, _ = await loop.create_connection(lambda: protocol, host, port, **kwds)\n",
    "    writer = StreamWriter(transport, protocol, reader, loop)\n",
    "    return reader, writer\n",
    "```\n",
    "发现，其实内部核心在`loop.create_connection`中\n",
    "```py\n",
    "# asyncio.base_events.py\n",
    "# 连接TCP服务器\n",
    "class BaseEventLoop(events.AbstractEventLoop):\n",
    "    async def create_connection(self,\n",
    "                                protocol_factory,\n",
    "                                host=None,\n",
    "                                port=None,\n",
    "                                *,\n",
    "                                ssl=None,\n",
    "                                family=0,\n",
    "                                proto=0,\n",
    "                                flags=0,\n",
    "                                sock=None,\n",
    "                                local_addr=None,\n",
    "                                server_hostname=None,\n",
    "                                ssl_handshake_timeout=None):\n",
    "        ...\n",
    "        # 主要逻辑\n",
    "        if host is not None or port is not None:\n",
    "            exceptions = []\n",
    "            # 主要逻辑\n",
    "            for family, type, proto, cname, address in infos:\n",
    "                try:\n",
    "                    sock = socket.socket(family=family, type=type, proto=proto)\n",
    "                    sock.setblocking(False) # 1.设置非阻塞 <<<< look\n",
    "                    if local_addr is not None:\n",
    "                        for _, _, _, _, laddr in laddr_infos:\n",
    "                            try:\n",
    "                                sock.bind(laddr) # 端口绑定\n",
    "                                break\n",
    "                            except OSError as exc:\n",
    "                                msg = (f'error while attempting to bind on '\n",
    "                                       f'address {laddr!r}: '\n",
    "                                       f'{exc.strerror.lower()}')\n",
    "                                exc = OSError(exc.errno, msg)\n",
    "                                exceptions.append(exc)\n",
    "                        else:\n",
    "                            sock.close()\n",
    "                            sock = None\n",
    "                            continue\n",
    "                    if self._debug:\n",
    "                        logger.debug(\"connect %r to %r\", sock, address)\n",
    "                    # 在selector_events中\n",
    "                    await self.sock_connect(sock, address) # <<< look\n",
    "                except OSError as exc:\n",
    "                    if sock is not None:\n",
    "                        sock.close()\n",
    "                    exceptions.append(exc)\n",
    "                except:\n",
    "                    if sock is not None:\n",
    "                        sock.close()\n",
    "                    raise\n",
    "                else:\n",
    "                    break\n",
    "```\n",
    "发现源码中**设置了socket为非阻塞**，调用了`sock_connect`\n",
    "```py\n",
    "async def sock_connect(self, sock, address):\n",
    "        \"\"\"连接远程socket地址(协程方法)\"\"\"\n",
    "        # 非阻塞检查\n",
    "        if self._debug and sock.gettimeout() != 0:\n",
    "            raise ValueError(\"the socket must be non-blocking\")\n",
    "        ...\n",
    "        fut = self.create_future()\n",
    "        self._sock_connect(fut, sock, address)\n",
    "        return await fut\n",
    "\n",
    "def _sock_connect(self, fut, sock, address):\n",
    "        fd = sock.fileno() # 获取socket的文件描述符 <<< look\n",
    "        try:\n",
    "            sock.connect(address)\n",
    "        except (BlockingIOError, InterruptedError):\n",
    "            # 设置future的回调函数_sock_connect_done（用来注销的）<<< look\n",
    "            fut.add_done_callback(functools.partial(self._sock_connect_done, fd))\n",
    "            # 注册selector.register\n",
    "            self.add_writer(fd, self._sock_connect_cb, fut, sock, address)\n",
    "        except Exception as exc:\n",
    "            fut.set_exception(exc)\n",
    "        else:\n",
    "            fut.set_result(None)\n",
    "```\n",
    "先看下`sock_connect`中调用的`add_writer`(注册)\n",
    "```py\n",
    "def add_writer(self, fd, callback, *args):\n",
    "    \"\"\"添加一个写的回调\"\"\"\n",
    "    self._ensure_fd_no_transport(fd)\n",
    "    return self._add_writer(fd, callback, *args)\n",
    "\n",
    "def _add_writer(self, fd, callback, *args):\n",
    "        self._check_closed()\n",
    "        handle = events.Handle(callback, args, self, None)\n",
    "        try:\n",
    "            key = self._selector.get_key(fd)\n",
    "        except KeyError:\n",
    "            self._selector.register(fd, selectors.EVENT_WRITE,\n",
    "                                    (None, handle)) # selector.register\n",
    "        else:\n",
    "            mask, (reader, writer) = key.events, key.data\n",
    "            self._selector.modify(fd, mask | selectors.EVENT_WRITE,\n",
    "                                  (reader, handle))\n",
    "            if writer is not None:\n",
    "                writer.cancel()\n",
    "```\n",
    "再看下`sock_connect`中设置的回调函数`_sock_connect_done`（注销）\n",
    "```py\n",
    "def _sock_connect_done(self, fd, fut):\n",
    "    # 取消注册selector.unregister\n",
    "    self.remove_writer(fd)\n",
    "    \n",
    "def remove_writer(self, fd):\n",
    "    \"\"\"移除写的回调\"\"\"\n",
    "    self._ensure_fd_no_transport(fd)\n",
    "    return self._remove_writer(fd)\n",
    "\n",
    "def _remove_writer(self, fd):\n",
    "    if self.is_closed():\n",
    "        return False\n",
    "    try:\n",
    "        key = self._selector.get_key(fd)\n",
    "    except KeyError:\n",
    "        return False\n",
    "    else:\n",
    "        mask, (reader, writer) = key.events, key.data\n",
    "        mask &= ~selectors.EVENT_WRITE\n",
    "        if not mask:\n",
    "            self._selector.unregister(fd) # 注销 <<< look\n",
    "        else:\n",
    "            self._selector.modify(fd, mask, (reader, None))\n",
    "\n",
    "        if writer is not None:\n",
    "            writer.cancel()\n",
    "            return True\n",
    "        else:\n",
    "            return False\n",
    "```\n",
    "\n",
    "**PS：嵌套的非常深，而且底层代码一致在变（Python3.6到Python3.7这个新小更新就变化很大）**\n",
    "\n",
    "### 关于源码的说明\n",
    "\n",
    "之前并发编程的基础知识已经讲的很清楚了，也分析了很多源码，你可以自己去拓展一下（`Python3`的`asyncio`模块的源码一直在优化改进的路上）我这边就不一一分析了(源码很乱，估计几个版本后会清晰，现在是多层混套用)，你可以参考部分源码解析：<https://github.com/lotapp/cpython3/tree/master/Lib/asyncio>\n",
    "![7.源码.png](https://img2018.cnblogs.com/blog/1127869/201901/1127869-20190107142010157-1086973041.png)\n",
    "\n",
    "课后拓展：\n",
    "```\n",
    "https://docs.python.org/3/library/asyncio-protocol.html#examples\n",
    "https://docs.python.org/3/library/asyncio-eventloop.html#creating-network-servers\n",
    "```\n",
    "\n",
    "下节预估：**同步与通信、aiohttp版爬虫**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "### 3.5.9.同步与通信\n",
    "\n",
    "官方文档：\n",
    "```\n",
    "https://docs.python.org/3/library/asyncio-sync.html\n",
    "https://docs.python.org/3/library/asyncio-queue.html\n",
    "```\n",
    "写在前面：\n",
    "1. **下面的方式不是线程安全的（协程就一个线程）**\n",
    "2. **这些同步原语的方法不接受超时参数; 使用asyncio.wait_for(协程方法,超时时间)函数执行超时操作**\n",
    "3. `asyncio`具有以下基本同步原语：`Lock、Event、Condition、Semaphore、BoundedSemaphore`\n",
    "\n",
    "#### 1.引导示例\n",
    "\n",
    "##### 1.1.old code\n",
    "\n",
    "先看个原来的引导案例：估计的结果是0，而不借助lock得出的结果往往出乎意料\n",
    "```py\n",
    "import concurrent.futures\n",
    "\n",
    "num = 0\n",
    "\n",
    "def test(i):\n",
    "    global num\n",
    "    for _ in range(10000000):\n",
    "        num += i\n",
    "\n",
    "def main():\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        print(\"start submit...\")\n",
    "        future1 = executor.submit(test, 1)\n",
    "        future2 = executor.submit(test, -1)\n",
    "        concurrent.futures.wait([future1, future2])  # wait some time\n",
    "        print(\"end submit...\")\n",
    "    global num\n",
    "    print(num)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "    main()\n",
    "    print(f\"time:{time.time()-start_time}\")\n",
    "```\n",
    "输出：(但是代码并不是线程安全的，所以结果往往不是我们想要的）\n",
    "```\n",
    "start submit...\n",
    "end submit...\n",
    "82705\n",
    "time:5.032064199447632\n",
    "```\n",
    "\n",
    "##### 1.2.new code\n",
    "\n",
    "再看看协程的案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "num = 0\n",
    "\n",
    "async def test(i):\n",
    "    global num\n",
    "    for _ in range(10000000):\n",
    "        num += i\n",
    "\n",
    "async def main():\n",
    "    print(\"start tasks...\")\n",
    "    task1 = asyncio.create_task(test(1))\n",
    "    task2 = asyncio.create_task(test(-1))\n",
    "    await asyncio.gather(task1, task2)\n",
    "    print(\"end tasks...\")\n",
    "\n",
    "    global num\n",
    "    print(num)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(f\"time:{time.time()-start_time}\")\n",
    "```\n",
    "输出：（就一个线程，当然安全）\n",
    "```\n",
    "start tasks...\n",
    "end tasks...\n",
    "0\n",
    "time:4.860997438430786\n",
    "```\n",
    "\n",
    "##### 1.3.注意点\n",
    "\n",
    "PS：**你使用协程的兼容代码，并不能解决线程不安全的问题**\n",
    "```\n",
    "import asyncio\n",
    "import concurrent.futures\n",
    "\n",
    "num = 0\n",
    "\n",
    "def test(i):\n",
    "    global num\n",
    "    for _ in range(10000000):\n",
    "        num += i\n",
    "\n",
    "async def main():\n",
    "    # 获取当前loop\n",
    "    loop = asyncio.get_running_loop()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        print(\"start submit...\")\n",
    "        future1 = loop.run_in_executor(executor, test, 1)\n",
    "        future2 = loop.run_in_executor(executor, test, -1)\n",
    "        # await asyncio.wait([future1,future2])\n",
    "        await asyncio.gather(future1, future2)\n",
    "        print(\"end submit...\")\n",
    "    global num\n",
    "    print(num)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(f\"time:{time.time()-start_time}\")\n",
    "```\n",
    "输出：\n",
    "```\n",
    "start submit...\n",
    "end submit...\n",
    "-1411610\n",
    "time:5.0279998779296875\n",
    "```\n",
    "\n",
    "#### 2.为什么需要同步机制？\n",
    "\n",
    "咋一看，单线程不用管线程安全啥的啊，要啥同步机制？其实在业务场景里面还是会出现诸如重复请求的情况，这个时候就需要一个同步机制了：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 用来存放页面缓存\n",
    "cache_dict = {}\n",
    "\n",
    "# 模拟一个获取html的过程\n",
    "async def fetch(url):\n",
    "    # 每次网络访问，时间其实不确定的\n",
    "    import random\n",
    "    time = random.randint(2, 5)\n",
    "    print(time)\n",
    "\n",
    "    await asyncio.sleep(time)\n",
    "    return f\"<h2>{url}</h2>\"\n",
    "\n",
    "async def get_html(url):\n",
    "    # 如果缓存存在，则返回缓存的页面\n",
    "    for url in cache_dict:\n",
    "        return cache_dict[url]\n",
    "    # 否则获取页面源码并缓存\n",
    "    html = await fetch(url)\n",
    "    cache_dict[url] = html\n",
    "    return html\n",
    "\n",
    "async def parse_js(url):\n",
    "    html = await get_html(url)\n",
    "    # do somthing\n",
    "    return len(html)\n",
    "\n",
    "async def parse_html(url):\n",
    "    html = await get_html(url)\n",
    "    # do somthing\n",
    "    return html\n",
    "\n",
    "async def main():\n",
    "    # 提交两个Task任务\n",
    "    task1 = asyncio.create_task(parse_js(\"www.baidu.com\"))\n",
    "    task2 = asyncio.create_task(parse_html(\"www.baidu.com\"))\n",
    "    # 等待任务结束\n",
    "    result_list = await asyncio.gather(task1, task2)\n",
    "    print(result_list)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：(`fetch`方法访问了两次 ==> 两次网络请求)\n",
    "```\n",
    "2\n",
    "3\n",
    "[22, '<h2>www.baidu.com</h2>']\n",
    "3.0100157260894775\n",
    "```\n",
    "\n",
    "**简单说明：`baidu.com`一开始没缓存，那当解析js和解析html的任务提交时，就会进行两次网络请求（网络IO比较耗时），这样更容易触发反爬虫机制**\n",
    "\n",
    "#### 3.Lock（互斥锁）\n",
    "\n",
    "线程相关的Lock复习：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#2.2.1.线程同步~互斥锁Lock>\n",
    "\n",
    "协程是线程安全的，那么这个`Lock`肯定是和`多线程/进程`里面的`Lock`是不一样的，我们先看一下提炼版的源码：\n",
    "```py\n",
    "class Lock(_ContextManagerMixin):\n",
    "    def __init__(self, *, loop=None):\n",
    "        self._waiters = collections.deque()\n",
    "        self._locked = False\n",
    "        if loop is not None:\n",
    "            self._loop = loop\n",
    "        else:\n",
    "            self._loop = events.get_event_loop()\n",
    "\n",
    "    async def acquire(self):\n",
    "        if not self._locked:\n",
    "            self._locked = True  # 改变标识\n",
    "        ...\n",
    "        return self._locked\n",
    "\n",
    "    def release(self):\n",
    "        if self._locked:\n",
    "            self._locked = False\n",
    "        ...\n",
    "```\n",
    "**PS：源码看完秒懂了，asyncio里面的lock其实就是一个标识而已**\n",
    "\n",
    "修改一下上面的例子：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "# 用来存放页面缓存\n",
    "cache_dict = {}\n",
    "lock = None  # 你可以试试在这边直接写`asyncio.Lock()`\n",
    "\n",
    "# 模拟一个获取html的过程\n",
    "async def fetch(url):\n",
    "    # 每次网络访问，时间其实不确定的\n",
    "    import random\n",
    "    time = random.randint(2, 5)\n",
    "    print(time)\n",
    "\n",
    "    await asyncio.sleep(time)\n",
    "    return f\"<h2>{url}</h2>\"\n",
    "\n",
    "\n",
    "async def get_html(url):\n",
    "    async with lock:\n",
    "        # 如果缓存存在，则返回缓存的页面\n",
    "        for url in cache_dict:\n",
    "            return cache_dict[url]\n",
    "        # 否则获取页面源码并缓存\n",
    "        html = await fetch(url)\n",
    "        cache_dict[url] = html\n",
    "        return html\n",
    "\n",
    "async def parse_js(url):\n",
    "    html = await get_html(url)\n",
    "    # do somthing\n",
    "    return len(html)\n",
    "\n",
    "async def parse_html(url):\n",
    "    html = await get_html(url)\n",
    "    # do somthing\n",
    "    return html\n",
    "\n",
    "async def main():\n",
    "    global lock\n",
    "    lock = asyncio.Lock()  # 如果在开头就定义，那么lock的loop和方法的loop就会不一致了\n",
    "\n",
    "    # 提交两个Task任务\n",
    "    task1 = asyncio.create_task(parse_js(\"www.baidu.com\"))\n",
    "    task2 = asyncio.create_task(parse_html(\"www.baidu.com\"))\n",
    "    # 等待任务结束\n",
    "    result_list = await asyncio.gather(task1, task2)\n",
    "    print(result_list)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出:(`fetch`方法访问了1次 ==> 1次网络请求)\n",
    "```\n",
    "3\n",
    "[22, '<h2>www.baidu.com</h2>']\n",
    "3.0020127296447754\n",
    "```\n",
    "\n",
    "#### 4.Semaphore（信号量）\n",
    "\n",
    "线程篇`Semaphore`：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#2.2.5.线程同步~信号量Semaphore(互斥锁的高级版)>\n",
    "\n",
    "这个用的比较多，简单回顾下之前讲的概念案例：\n",
    "\n",
    "**通俗讲就是：在互斥锁的基础上封装了下，实现一定程度的并行**\n",
    "\n",
    "举个例子，以前使用互斥锁的时候：（厕所就一个坑位，必须等里面的人出来才能让另一个人上厕所）\n",
    "\n",
    "![2018-08-23/3.互斥锁.png](https://images2018.cnblogs.com/blog/1127869/201808/1127869-20180825091044646-291098504.png)\n",
    "\n",
    "使用信号量`Semaphore`之后：厕所坑位增加到5个（自己指定），这样可以5个人一起上厕所了==> 实现了一定程度的并发控制\n",
    "\n",
    "先看下缩略的源码：（可以这么想：**内部维护了一个引用计数，每次来个任务就-1，一个任务结束计数就+1**）\n",
    "```py\n",
    "class Semaphore(_ContextManagerMixin):\n",
    "    def __init__(self, value=1, *, loop=None):\n",
    "        if value < 0:\n",
    "            raise ValueError(\"Semaphore initial value must be >= 0\")\n",
    "        self._value = value\n",
    "        self._waiters = collections.deque()\n",
    "        if loop is not None:\n",
    "            self._loop = loop\n",
    "        else:\n",
    "            self._loop = events.get_event_loop()\n",
    "\n",
    "    async def acquire(self):\n",
    "        while self._value <= 0:\n",
    "            fut = self._loop.create_future()\n",
    "            self._waiters.append(fut) # 把当前任务放入Queue中\n",
    "            try:\n",
    "                await fut # 等待一个任务的完成再继续\n",
    "            except:\n",
    "                fut.cancel() # 任务取消\n",
    "                if self._value > 0 and not fut.cancelled():\n",
    "                    self._wake_up_next() # 唤醒下一个任务\n",
    "                raise\n",
    "        self._value -= 1 # 用掉一个并发量\n",
    "        return True\n",
    "\n",
    "    def release(self):\n",
    "        self._value += 1 # 恢复一个并发量\n",
    "        self._wake_up_next() # 唤醒下一个任务\n",
    "```\n",
    "\n",
    "现在举个常见的场景：**比如调用某个免费的api，该api限制并发数为5**\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "sem = None\n",
    "\n",
    "# 模拟api请求\n",
    "async def api_test(i):\n",
    "    async with sem:\n",
    "        await asyncio.sleep(1)\n",
    "        print(f\"The Task {i} is done\")\n",
    "\n",
    "async def main():\n",
    "    global sem\n",
    "    sem = asyncio.Semaphore(5)  # 设置并发数为5\n",
    "    tasks = [asyncio.create_task(api_test(i)) for i in range(20)]\n",
    "    await asyncio.gather(*tasks)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "动态输出：\n",
    "![2018-12-07/11.sem.gif](https://img2018.cnblogs.com/blog/1127869/201901/1127869-20190124143730089-177887850.gif)\n",
    "\n",
    "**PS：`BoundedSemaphore`是`Semaphore`的一个版本，在调用`release()`时检查计数器的值是否超过了计数器的初始值，如果超过了就抛出一个异常**\n",
    "\n",
    "#### 5.Event（事件）\n",
    "\n",
    "线程篇`Event`：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#2.2.8.线程同步~Event>\n",
    "\n",
    "之前讲的很详细了，举个`爬虫批量更新`的例子就一笔带过：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "event = None\n",
    "html_dict = {}\n",
    "\n",
    "async def updates():\n",
    "    # event.wait()是协程方法，需要await\n",
    "    await event.wait()\n",
    "    # 入库操作省略 html_dict >> DB\n",
    "    return \"html_dict >> DB done\"\n",
    "\n",
    "async def get_html(url):\n",
    "    # 摸拟网络请求\n",
    "    await asyncio.sleep(2)\n",
    "    html_dict[url] = f\"<h1>{url}</h1>\" # 可以暂时写入临时文件中\n",
    "\n",
    "    event.set()  # 标记完成，普通方法\n",
    "    return f\"{url} done\"\n",
    "\n",
    "async def main():\n",
    "    global event\n",
    "    event = asyncio.Event()  # 初始化 event 对象\n",
    "\n",
    "    # 创建批量任务\n",
    "    tasks = [\n",
    "        asyncio.create_task(get_html(f\"www.mmd.com/a/{i}\"))\n",
    "        for i in range(1, 10)\n",
    "    ]\n",
    "    # 批量更新操作\n",
    "    tasks.append(asyncio.create_task(updates()))\n",
    "    \n",
    "    result = await asyncio.gather(*tasks)\n",
    "    print(result)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "['www.mmd.com/a/1 done', 'www.mmd.com/a/2 done', 'www.mmd.com/a/3 done', 'www.mmd.com/a/4 done', 'www.mmd.com/a/5 done', 'www.mmd.com/a/6 done', 'www.mmd.com/a/7 done', 'www.mmd.com/a/8 done', 'www.mmd.com/a/9 done', 'html_dict >> DB done']\n",
    "2.0012683868408203\n",
    "```\n",
    "\n",
    "跟之前基本上一样，就一个地方不太一样：`async def wait(self)`，`wait`方法现在是协程方法了，使用的时候需要`await`\n",
    "1. **`coroutine wait()`**\n",
    "    - 等待事件内部标志被设置为`True`\n",
    "    - 如果事件的内部内部标志已设置，则立即返回`True`。否则，一直阻塞，直到另外的任务调用`set()`\n",
    "2. **`set()`**\n",
    "    - 设置事件内部标志为`True`\n",
    "    - 所有等待事件的任务将会立即被触发\n",
    "3. **`clear()`**\n",
    "    - 清除事件内部标志（即重置为`False`）\n",
    "    - 等待事件的任务将会阻塞，直到`set()`方法被再次调用\n",
    "4. **`is_set()`**\n",
    "    - 如果事件内部标志被设置为`True`，则返回`True`\n",
    "\n",
    "#### 6.Condition（条件变量）\n",
    "\n",
    "线程篇`Condition`：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#2.2.4.线程同步~条件变量Condition>\n",
    "\n",
    "先简单看看方法列表：\n",
    "1. **`coroutine acquire()`**：\n",
    "    - 获取底层锁。该方法一直等待，直到底层锁处于未锁定状态，然后设置其为锁定状态，并且返回True\n",
    "2. `notify(n=1)`：\n",
    "    - 唤醒至多n个等待条件的任务。如果没有正在等待的任务，则该方法无操作。\n",
    "    - 在调用该方法之前，必须先调用`acquire()`获取锁，并在调用该方法之后释放锁。\n",
    "    - 如果在锁为锁定的情况下调用此方法，会引发`RuntimeError`异常。\n",
    "3. `locked()`：\n",
    "    - 如果底层锁已获取，则返回True。\n",
    "4. `notify_all()`：\n",
    "    - 唤醒所有正在等待该条件的任务。该方法与notify()类似，区别只在它会唤醒所有正在等待的任务。\n",
    "5. `release()`：\n",
    "    - 释放底层锁。在未锁定的锁上调用时，会引发RuntimeError异常。\n",
    "6. **`coroutine wait()`**：\n",
    "    - 等待通知。如果调用此方法的任务没有获取到锁，则引发RuntimeError异常。\n",
    "    - 此方法释放底层锁，然后保持阻塞，直至被notify()或notify_all()唤醒。被唤醒之后，条件对象重新申请锁，该方法返回True。\n",
    "7. **`coroutine wait_for(predicate)`**\n",
    "    - 等待`predicate`变为True。`predicate`必须可调用，它的执行结果会被解释为布尔值，并作为最终结果返回。\n",
    "\n",
    "PS：**`Condition`结合了`Event`和`Lock`的功能**(也可以使多个Condition对象共享一个Lock，允许不同任务之间协调对共享资源的独占访问)\n",
    "\n",
    "看个生产消费者的案例：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "cond = None\n",
    "p_list = []\n",
    "\n",
    "# 生产者\n",
    "async def producer(n):\n",
    "    for i in range(5):\n",
    "        async with cond:\n",
    "            p_list.append(f\"{n}-{i}\")\n",
    "            print(f\"[生产者{n}]生产商品{n}-{i}\")\n",
    "            # 通知任意一个消费者\n",
    "            cond.notify()  # 通知全部消费者：cond.notify_all()\n",
    "        # 摸拟一个耗时操作\n",
    "        await asyncio.sleep(0.01)\n",
    "\n",
    "# 消费者\n",
    "async def consumer(i):\n",
    "    while True:\n",
    "        async with cond:\n",
    "            if p_list:\n",
    "                print(f\"列表商品：{p_list}\")\n",
    "                name = p_list.pop()  # 消费商品\n",
    "                print(f\"[消费者{i}]消费商品{name}\")\n",
    "                print(f\"列表剩余：{p_list}\")\n",
    "\n",
    "                # 摸拟一个耗时操作\n",
    "                await asyncio.sleep(0.01)\n",
    "            else:\n",
    "                await cond.wait()\n",
    "\n",
    "async def main():\n",
    "    global cond\n",
    "    cond = asyncio.Condition()  # 初始化condition\n",
    "    p_tasks = [asyncio.create_task(producer(i)) for i in range(2)]  # 两个生产者\n",
    "    c_tasks = [asyncio.create_task(consumer(i)) for i in range(5)]  # 五个消费者\n",
    "    await asyncio.gather(*p_tasks, *c_tasks)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    asyncio.run(main())\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[生产者0]生产商品0-0\n",
    "[生产者1]生产商品1-0\n",
    "列表商品：['0-0', '1-0']\n",
    "[消费者0]消费商品1-0\n",
    "列表剩余：['0-0']\n",
    "列表商品：['0-0']\n",
    "[消费者1]消费商品0-0\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品0-1\n",
    "[生产者1]生产商品1-1\n",
    "列表商品：['0-1', '1-1']\n",
    "[消费者0]消费商品1-1\n",
    "列表剩余：['0-1']\n",
    "列表商品：['0-1']\n",
    "[消费者1]消费商品0-1\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品0-2\n",
    "[生产者1]生产商品1-2\n",
    "列表商品：['0-2', '1-2']\n",
    "[消费者0]消费商品1-2\n",
    "列表剩余：['0-2']\n",
    "列表商品：['0-2']\n",
    "[消费者1]消费商品0-2\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品0-3\n",
    "[生产者1]生产商品1-3\n",
    "列表商品：['0-3', '1-3']\n",
    "[消费者0]消费商品1-3\n",
    "列表剩余：['0-3']\n",
    "列表商品：['0-3']\n",
    "[消费者1]消费商品0-3\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品0-4\n",
    "[生产者1]生产商品1-4\n",
    "列表商品：['0-4', '1-4']\n",
    "[消费者0]消费商品1-4\n",
    "列表剩余：['0-4']\n",
    "列表商品：['0-4']\n",
    "[消费者1]消费商品0-4\n",
    "列表剩余：[]\n",
    "```\n",
    "\n",
    "PS：第七条的简单说明：（来看看`wait_for`方法的源码）\n",
    "```py\n",
    "# 一直等到函数返回true（从返回结果来说：要么一直阻塞，要么返回true）\n",
    "async def wait_for(self, predicate):\n",
    "    result = predicate()\n",
    "    # 如果不是返回true就继续等待\n",
    "    while not result:\n",
    "        await self.wait()\n",
    "        result = predicate()\n",
    "    return result\n",
    "```\n",
    "\n",
    "课后拓展：`async_timeout`（兼容async的超时的上下文管理器）\n",
    "<https://github.com/lotapp/BaseCode/blob/master/python/5.concurrent/ZCoroutine/async_timeout_timeout.py>\n",
    "\n",
    "#### 7.Queue（队列）\n",
    "\n",
    "官方文档：<https://docs.python.org/3/library/asyncio-queue.html>\n",
    "\n",
    "线程篇`Queue`：<https://www.cnblogs.com/dotnetcrazy/p/9528315.html#2.2.6.线程同步~Queue-引入>\n",
    "\n",
    "其实你不考虑限流的情况下，协程里面的queue和list基本上差不多（ps：`asyncio.Queue(num)`可以指定数量）\n",
    "\n",
    "举个经典的生产消费者案例：\n",
    "```py\n",
    "import random\n",
    "import asyncio\n",
    "\n",
    "async def producer(q, i):\n",
    "    for i in range(5):\n",
    "        num = random.random()\n",
    "        await q.put(num)\n",
    "        print(f\"[生产者{i}]商品{num}出厂了\")\n",
    "        await asyncio.sleep(num)\n",
    "\n",
    "async def consumer(q, i):\n",
    "    while True:\n",
    "        data = await q.get()\n",
    "        print(f\"[消费者{i}]商品{data}抢光了\")\n",
    "\n",
    "async def main():\n",
    "    queue = asyncio.Queue(10)  # 为了演示，我这边限制一下\n",
    "\n",
    "    p_tasks = [asyncio.create_task(producer(queue, i)) for i in range(2)]  # 两个生产者\n",
    "    c_tasks = [asyncio.create_task(consumer(queue, i)) for i in range(5)]  # 五个消费者\n",
    "    await asyncio.gather(*p_tasks, *c_tasks)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（注意一下`get`和`put`方法都是协程方法即可）\n",
    "```\n",
    "[生产者0]商品0.20252203397767787出厂了\n",
    "[生产者0]商品0.9641503458079388出厂了\n",
    "[消费者0]商品0.20252203397767787抢光了\n",
    "[消费者0]商品0.9641503458079388抢光了\n",
    "[生产者1]商品0.8049655468032324出厂了\n",
    "[消费者0]商品0.8049655468032324抢光了\n",
    "[生产者1]商品0.6032743557097342出厂了\n",
    "[消费者1]商品0.6032743557097342抢光了\n",
    "[生产者2]商品0.08818326334746773出厂了\n",
    "[消费者2]商品0.08818326334746773抢光了\n",
    "[生产者3]商品0.3747289313977561出厂了\n",
    "[消费者3]商品0.3747289313977561抢光了\n",
    "[生产者4]商品0.3948823110071299出厂了\n",
    "[消费者4]商品0.3948823110071299抢光了\n",
    "[生产者2]商品0.5775767044660681出厂了\n",
    "[消费者0]商品0.5775767044660681抢光了\n",
    "[生产者3]商品0.500537752889471出厂了\n",
    "[消费者1]商品0.500537752889471抢光了\n",
    "[生产者4]商品0.9921528527523727出厂了\n",
    "[消费者2]商品0.9921528527523727抢光了\n",
    "```\n",
    "\n",
    "PS：协程也提供了**`Priority Queue`优先级队列 and `LifoQueue`后进先出队列**，这边就不再啰嗦了(前面我们**画图演示并手动实现过**)\n",
    "\n",
    "课后拓展：<https://docs.python.org/3/library/asyncio-queue.html#examples>\n",
    "\n",
    "### 扩展：Subprocesses\n",
    "\n",
    "官方文档：<https://docs.python.org/3/library/asyncio-subprocess.html>\n",
    "\n",
    "这个之前进程篇的时候说过，不是我们今天的重点，我贴一个官方demo：\n",
    "```py\n",
    "import asyncio\n",
    "\n",
    "async def run(cmd):\n",
    "    proc = await asyncio.create_subprocess_shell(\n",
    "        cmd,\n",
    "        stdout=asyncio.subprocess.PIPE,\n",
    "        stderr=asyncio.subprocess.PIPE)\n",
    "\n",
    "    stdout, stderr = await proc.communicate()\n",
    "\n",
    "    print(f'[{cmd!r} exited with {proc.returncode}]')\n",
    "    if stdout:\n",
    "        print(f'[stdout]\\n{stdout.decode()}')\n",
    "    if stderr:\n",
    "        print(f'[stderr]\\n{stderr.decode()}')\n",
    "\n",
    "asyncio.run(run('ls /zzz'))\n",
    "```\n",
    "输出：\n",
    "```\n",
    "['ls /zzz' exited with 1]\n",
    "[stderr]\n",
    "ls: /zzz: No such file or directory\n",
    "```\n",
    "\n",
    "下节预告：**`asyncio`+`aiohttp`版爬虫**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 4.aiohttp\n",
    "\n",
    "代码：<https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/ZCoroutine/z_spider>\n",
    "\n",
    "`asyncio`库只有`TCP`和`UDP`服务，并不支持`HTTP`，`aiohttp`就可以理解为是基于`asyncio`的`http`服务\n",
    "\n",
    "### 4.1.入门案例\n",
    "\n",
    "先来个获取页面html的demo：\n",
    "```py\n",
    "import asyncio\n",
    "import aiohttp\n",
    "\n",
    "error_urls = set()\n",
    "\n",
    "# 获取页面html\n",
    "async def fetch(session, url):\n",
    "    async with session.get(url) as response:\n",
    "        if response.status == 200:\n",
    "            return await response.text()\n",
    "        else:\n",
    "            error_urls.add(url)  # 添加到待处理集合中\n",
    "\n",
    "async def main():\n",
    "    async with aiohttp.ClientSession() as session:\n",
    "        html = await fetch(session, \"http://www.biquge.cm/12/12097/\")\n",
    "        if html:  # 获取到html\n",
    "            print(len(html))\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "24287\n",
    "0.5429983139038086\n",
    "```\n",
    "\n",
    "### 4.2.html解析\n",
    "\n",
    "推荐一款轻量级网页解析库：**`pyquery`**（一个类似jquery的python库）\n",
    "\n",
    "#### 4.2.1.列表页\n",
    "\n",
    "在上面基础上简单提取：（`pq.items(\"dd a\")` ==> 类比JQ选择器）\n",
    "```py\n",
    "import asyncio\n",
    "import aiohttp\n",
    "from pyquery import PyQuery\n",
    "\n",
    "error_urls = set()\n",
    "\n",
    "# 获取页面html\n",
    "async def fetch(session, url):\n",
    "    async with session.get(url) as response:\n",
    "        if response.status == 200:\n",
    "            return await response.text()\n",
    "        else:\n",
    "            error_urls.add(url)  # 待处理的url集合\n",
    "\n",
    "# 阻塞方法\n",
    "def saves(results):\n",
    "    with open(\"www.biquge.cm.txt\", \"a+\", encoding=\"utf-8\") as fs:\n",
    "        fs.writelines(results)\n",
    "        print(\"ok\")\n",
    "\n",
    "async def main():\n",
    "    async with aiohttp.ClientSession() as session:\n",
    "        html = await fetch(session, \"http://www.biquge.cm/12/12097/\")\n",
    "        pq = PyQuery(html)\n",
    "\n",
    "        results = [\n",
    "            item.text() + \":\" + item.attr(\"href\") + \"\\n\"\n",
    "            for item in pq.items(\"dd a\")\n",
    "        ]\n",
    "        # print(pq(\"dd a\").text())\n",
    "        \n",
    "        # 兼容阻塞旧代码\n",
    "        await asyncio.get_running_loop().run_in_executor(None, saves, results)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：`www.biquge.cm.txt`\n",
    "```\n",
    "新书的一些话:/12/12097/7563947.html\n",
    "第一章论坛里的鬼故事。:/12/12097/7563949.html\n",
    "第二章临时讲课:/12/12097/7563950.html\n",
    "第三章鬼域。:/12/12097/7563951.html\n",
    "第四章恐怖敲门鬼:/12/12097/7565568.html\n",
    "第五章迷路:/12/12097/7565569.html\n",
    "第六章厕所中的手:/12/12097/7565570.html\n",
    "第七章身后的脚步:/12/12097/7565571.html\n",
    "第八章奇怪的树:/12/12097/7565572.html\n",
    "第九章鬼婴:/12/12097/7565573.html\n",
    "第十章恶鬼之力:/12/12097/7565574.html\n",
    "...\n",
    "第三百二十七章三口箱子:/12/12097/7950281.html\n",
    "第三百二十八章鬼橱里的照片:/12/12097/7952145.html\n",
    "第三百二十九章中山市事件:/12/12097/7955244.html\n",
    "第三百三十章两条信息:/12/12097/7956401.html\n",
    "第三百三十一章进入中山市:/12/12097/7959077.html\n",
    "第三百三十二章出乎意料:/12/12097/7962119.html\n",
    "第三百三十四章酒店的二楼:/12/12097/7964192.html\n",
    "第三百三十五章黑色的烛火:/12/12097/7969058.html\n",
    "第三百三十六章微笑的尸体:/12/12097/7973826.html\n",
    "```\n",
    "\n",
    "#### 4.2.2.详情页\n",
    "\n",
    "获取一个详情页看看：\n",
    "```py\n",
    "import asyncio\n",
    "import aiohttp\n",
    "from pyquery import PyQuery\n",
    "\n",
    "error_urls = set()\n",
    "\n",
    "# 获取页面html\n",
    "async def fetch(session, url):\n",
    "    async with session.get(url) as response:\n",
    "        if response.status == 200:\n",
    "            return await response.text()\n",
    "        else:\n",
    "            error_urls.add(url)  # 待处理的url集合\n",
    "\n",
    "# 详情页获取测试\n",
    "async def main():\n",
    "    async with aiohttp.ClientSession() as session:\n",
    "        html = await fetch(session,\n",
    "                           \"http://www.biquge.cm//12/12097/7563949.html\")\n",
    "        pq = PyQuery(html)\n",
    "        print(pq(\"#content\").text())\n",
    "        # results = [item.text() for item in pq.items(\"#content\")]\n",
    "        # print(results)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "老夫掐指一算，你现在正在床上看小说，而且还是侧身，搞不好手机还在充电。\n",
    "\n",
    "正在读高三的杨间此刻正躺在被窝里无聊的翻看着手机，他随手点开了一个帖子，下面有不少网友在回帖。\n",
    "\n",
    "“卧槽，楼主真乃神人也，这都被楼主猜中了。”\n",
    "\n",
    "“呵，你会告诉你们我现在正在厕所蹲坑么？不用问了，脚麻了。”\n",
    "\n",
    "......\n",
    "\n",
    "0.6684205532073975\n",
    "```\n",
    "\n",
    "**PS：Win下Py包安装出错就去这个网站下对应包** <https://www.lfd.uci.edu/~gohlke/pythonlibs/>\n",
    "\n",
    "### 4.3.爬虫小案例\n",
    "\n",
    "#### 4.3.1.小说网站实战\n",
    "\n",
    "限流以及反爬虫和如何应对反爬虫机制，后面我们会继续说，这边简单举个小说离线的例子：\n",
    "```py\n",
    "import asyncio\n",
    "import aiohttp\n",
    "from pyquery import PyQuery\n",
    "\n",
    "sem = None\n",
    "error_urls = set()\n",
    "\n",
    "# 获取html\n",
    "async def fetch(session, url):\n",
    "    async with sem:\n",
    "        async with session.get(url) as response:\n",
    "            if response.status == 200:\n",
    "                # aiohttp遇到非法字符的处理\n",
    "                return await response.text(\"gbk\", \"ignore\")  # 忽略非法字符\n",
    "            else:\n",
    "                error_urls.add(url)  # 待处理的url集合\n",
    "\n",
    "# 获取文章正文\n",
    "async def get_text(session, url):\n",
    "    # 把相对路径改成域名+路径\n",
    "    if not url.startswith(\"http://www.biquge.cm\"):\n",
    "        url = \"http://www.biquge.cm\" + url\n",
    "    html = await fetch(session, url)\n",
    "    pq = PyQuery(html)\n",
    "    return pq(\"#content\").text()\n",
    "\n",
    "# 普通阻塞方法\n",
    "def save(title, text):\n",
    "    with open(\"恐怖复苏.md\", \"a+\", encoding=\"gbk\") as fs:\n",
    "        fs.write(f\"## {title}\\n\\n{text}\\n\\n\")\n",
    "        print(f\"{title} done...\")\n",
    "\n",
    "async def main():\n",
    "    global sem\n",
    "    sem = asyncio.Semaphore(3) # 控制并发数反而更快\n",
    "    loop = asyncio.get_running_loop()\n",
    "\n",
    "    async with aiohttp.ClientSession() as session:\n",
    "        html = await fetch(session, \"http://www.biquge.cm/12/12097/\")\n",
    "        pq = PyQuery(html)\n",
    "        for item in pq.items(\"dd a\"):\n",
    "            title = item.text()\n",
    "            text = await get_text(session, item.attr(\"href\"))\n",
    "            # 兼容阻塞旧代码\n",
    "            await loop.run_in_executor(None, save, title, text)\n",
    "    print(\"task over\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "\n",
    "    asyncio.run(main())\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "```\n",
    "输出：（爬取整站就不用我说了吧：`提取a标签中的src，url去重后爬取内容`）\n",
    "```\n",
    "新书的一些话 done...\n",
    "第一章论坛里的鬼故事。 done...\n",
    "第二章临时讲课 done...\n",
    "第三章鬼域。 done...\n",
    "第四章恐怖敲门鬼 done...\n",
    "第五章迷路 done...\n",
    "第六章厕所中的手 done...\n",
    "第七章身后的脚步 done...\n",
    "第八章奇怪的树 done...\n",
    "第九章鬼婴 done...\n",
    "第十章恶鬼之力 done...\n",
    "第十一章逐渐复苏 done...\n",
    "第十二章宛如智障 done...\n",
    "第十三章羊皮纸 done...\n",
    "第十四章诡异的纸 done...\n",
    "......\n",
    "第三百二十八章鬼橱里的照片 done...\n",
    "第三百二十九章中山市事件 done...\n",
    "第三百三十章两条信息 done...\n",
    "第三百三十一章进入中山市 done...\n",
    "第三百三十二章出乎意料 done...\n",
    "第三百三十四章酒店的二楼 done...\n",
    "第三百三十五章黑色的烛火 done...\n",
    "第三百三十六章微笑的尸体 done...\n",
    "task over\n",
    "```\n",
    "动态展示：\n",
    "![动态展示](https://img2018.cnblogs.com/blog/658978/201902/658978-20190210012002862-3749285.gif)\n",
    "\n",
    "### 闲言碎语\n",
    "\n",
    "**【推荐】Python高性能异步框架**：<https://github.com/LessChina/sanic>\n",
    "\n",
    "逆天点评：（只看主线，只说我的见识）\n",
    "1. 原来大家都是使用大一统的`Django`（方便）\n",
    "2. 后来因为性能不佳，FaceBook开发了`Tornado`（IO多路复用）来代替\n",
    "3. 再后来时代主流是敏捷开发，于是就有了`Flask`（简单）\n",
    "4. 后来Node和Go火了，NetCore也出山了，Python的Flask等同步框架总是被吊打\n",
    "5. 于是被逼出了`Japronto`，瞬间惊艳和吊打的所有开发语言，但是只是冒了泡就不怎么维护了\n",
    "6. 后来就是AI爆发时期，Python直接打上了AI的标签了，而Web也逐渐被打上了初创公司的标配\n",
    "7. 之后官方看不下去了，自己搞了一套异步框架`asyncio`and`aiohttp`（Node兄弟这么优秀，凭啥我们不行）\n",
    "8. 民间看不下去了来了个`asyncio`替代品**`uvloop`**（C实现的程度比官方多(谁多谁高效)，PS：官方用法太丑陋了3.7才给足了语法糖）\n",
    "9. 解决方案虽然各种出，但是web框架不行啊，于是又冒了个主流**`sanic`**（语法和`Flask`很像，性能不亚于`Japronto`）\n",
    "10. 现在又刚冒出**`vibora`**（都是C实现）有超过`sanic`的趋势（PS：等过几个版本再试水，不过现在很多开发者都是`Go + Python`了)\n",
    "\n",
    "最后BB一句：\n",
    "1. `gevent`用猴子补丁的确很方便，但很多内部异常就被屏蔽了，而且性能现在不是最高\n",
    "2. `tornado`为了兼容`py2`和`py3`，内部还是通过生成器来实现异步的，效率相对低点\n",
    "3. `asyncio`是未来的主流方向，`sanic`是目前最火的异步框架（`vibora`还在观察中）\n",
    "\n",
    "PS：`Django`、`Flask`是阻塞式IO，web框架一般不会直接部署（它自带的解决方案只是方便调试），一般使用`uwsgi` or `gunicorn` + `nginx`来部署（tornado可以直接部署）\n",
    "\n",
    "参考链接：\n",
    "```\n",
    "python异步编程之asyncio\n",
    "https://www.cnblogs.com/shenh/p/9090586.html\n",
    "\n",
    "uWSGI, Gunicorn, 啥玩意儿?\n",
    "https://www.cnblogs.com/gdkl/p/6807667.html\n",
    "\n",
    "asyncio异步IO中文翻译：\n",
    "http://www.cnblogs.com/mamingqian/p/10008279.html\n",
    "https://www.cnblogs.com/mamingqian/p/10075444.html\n",
    "https://www.cnblogs.com/mamingqian/p/10044730.html\n",
    "\n",
    "PyQuery基础：\n",
    "https://www.cnblogs.com/zhaof/p/6935473.html\n",
    "https://www.cnblogs.com/lei0213/p/7676254.html\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
